babylon.mesh.ts 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  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. // Consts
  9. public static _FRONTSIDE: number = 0;
  10. public static _BACKSIDE: number = 1;
  11. public static _DOUBLESIDE: number = 2;
  12. public static _DEFAULTSIDE: number = 0;
  13. public static _NO_CAP = 0;
  14. public static _CAP_START = 1;
  15. public static _CAP_END = 2;
  16. public static _CAP_ALL = 3;
  17. public static get FRONTSIDE(): number {
  18. return Mesh._FRONTSIDE;
  19. }
  20. public static get BACKSIDE(): number {
  21. return Mesh._BACKSIDE;
  22. }
  23. public static get DOUBLESIDE(): number {
  24. return Mesh._DOUBLESIDE;
  25. }
  26. public static get DEFAULTSIDE(): number {
  27. return Mesh._DEFAULTSIDE;
  28. }
  29. public static get NO_CAP(): number {
  30. return Mesh._NO_CAP;
  31. }
  32. public static get CAP_START(): number {
  33. return Mesh._CAP_START;
  34. }
  35. public static get CAP_END(): number {
  36. return Mesh._CAP_END;
  37. }
  38. public static get CAP_ALL(): number {
  39. return Mesh._CAP_ALL;
  40. }
  41. // Members
  42. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  43. public instances = new Array<InstancedMesh>();
  44. public delayLoadingFile: string;
  45. public _binaryInfo: any;
  46. private _LODLevels = new Array<Internals.MeshLODLevel>();
  47. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  48. // Private
  49. public _geometry: Geometry;
  50. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  51. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  52. public _delayInfo; //ANY
  53. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  54. public _visibleInstances: any = {};
  55. private _renderIdForInstances = new Array<number>();
  56. private _batchCache = new _InstancesBatch();
  57. private _worldMatricesInstancesBuffer: WebGLBuffer;
  58. private _worldMatricesInstancesArray: Float32Array;
  59. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  60. public _shouldGenerateFlatShading: boolean;
  61. private _preActivateId: number;
  62. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  63. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  64. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  65. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  66. /**
  67. * @constructor
  68. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  69. * @param {Scene} scene - The scene to add this mesh to.
  70. * @param {Node} parent - The parent of this mesh, if it has one
  71. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  72. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  73. * When false, achieved by calling a clone(), also passing False.
  74. * This will make creation of children, recursive.
  75. */
  76. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  77. super(name, scene);
  78. if (source) {
  79. // Geometry
  80. if (source._geometry) {
  81. source._geometry.applyToMesh(this);
  82. }
  83. // Deep copy
  84. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  85. this.id = name + "." + source.id;
  86. // Material
  87. this.material = source.material;
  88. if (!doNotCloneChildren) {
  89. // Children
  90. for (var index = 0; index < scene.meshes.length; index++) {
  91. var mesh = scene.meshes[index];
  92. if (mesh.parent === source) {
  93. // doNotCloneChildren is always going to be False
  94. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  95. }
  96. }
  97. }
  98. // Particles
  99. for (index = 0; index < scene.particleSystems.length; index++) {
  100. var system = scene.particleSystems[index];
  101. if (system.emitter === source) {
  102. system.clone(system.name, this);
  103. }
  104. }
  105. this.computeWorldMatrix(true);
  106. }
  107. // Parent
  108. if (parent !== null) {
  109. this.parent = parent;
  110. }
  111. }
  112. // Methods
  113. public get hasLODLevels(): boolean {
  114. return this._LODLevels.length > 0;
  115. }
  116. private _sortLODLevels(): void {
  117. this._LODLevels.sort((a, b) => {
  118. if (a.distance < b.distance) {
  119. return 1;
  120. }
  121. if (a.distance > b.distance) {
  122. return -1;
  123. }
  124. return 0;
  125. });
  126. }
  127. /**
  128. * Add a mesh as LOD level triggered at the given distance.
  129. * @param {number} distance - the distance from the center of the object to show this level
  130. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  131. * @return {BABYLON.Mesh} this mesh (for chaining)
  132. */
  133. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  134. if (mesh && mesh._masterMesh) {
  135. Tools.Warn("You cannot use a mesh as LOD level twice");
  136. return this;
  137. }
  138. var level = new Internals.MeshLODLevel(distance, mesh);
  139. this._LODLevels.push(level);
  140. if (mesh) {
  141. mesh._masterMesh = this;
  142. }
  143. this._sortLODLevels();
  144. return this;
  145. }
  146. public getLODLevelAtDistance(distance: number): Mesh {
  147. for (var index = 0; index < this._LODLevels.length; index++) {
  148. var level = this._LODLevels[index];
  149. if (level.distance === distance) {
  150. return level.mesh;
  151. }
  152. }
  153. return null;
  154. }
  155. /**
  156. * Remove a mesh from the LOD array
  157. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  158. * @return {BABYLON.Mesh} this mesh (for chaining)
  159. */
  160. public removeLODLevel(mesh: Mesh): Mesh {
  161. for (var index = 0; index < this._LODLevels.length; index++) {
  162. if (this._LODLevels[index].mesh === mesh) {
  163. this._LODLevels.splice(index, 1);
  164. if (mesh) {
  165. mesh._masterMesh = null;
  166. }
  167. }
  168. }
  169. this._sortLODLevels();
  170. return this;
  171. }
  172. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  173. if (!this._LODLevels || this._LODLevels.length === 0) {
  174. return this;
  175. }
  176. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  177. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  178. if (this.onLODLevelSelection) {
  179. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  180. }
  181. return this;
  182. }
  183. for (var index = 0; index < this._LODLevels.length; index++) {
  184. var level = this._LODLevels[index];
  185. if (level.distance < distanceToCamera) {
  186. if (level.mesh) {
  187. level.mesh._preActivate();
  188. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  189. }
  190. if (this.onLODLevelSelection) {
  191. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  192. }
  193. return level.mesh;
  194. }
  195. }
  196. if (this.onLODLevelSelection) {
  197. this.onLODLevelSelection(distanceToCamera, this, this);
  198. }
  199. return this;
  200. }
  201. public get geometry(): Geometry {
  202. return this._geometry;
  203. }
  204. public getTotalVertices(): number {
  205. if (!this._geometry) {
  206. return 0;
  207. }
  208. return this._geometry.getTotalVertices();
  209. }
  210. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] {
  211. if (!this._geometry) {
  212. return null;
  213. }
  214. return this._geometry.getVerticesData(kind, copyWhenShared);
  215. }
  216. public getVertexBuffer(kind): VertexBuffer {
  217. if (!this._geometry) {
  218. return undefined;
  219. }
  220. return this._geometry.getVertexBuffer(kind);
  221. }
  222. public isVerticesDataPresent(kind: string): boolean {
  223. if (!this._geometry) {
  224. if (this._delayInfo) {
  225. return this._delayInfo.indexOf(kind) !== -1;
  226. }
  227. return false;
  228. }
  229. return this._geometry.isVerticesDataPresent(kind);
  230. }
  231. public getVerticesDataKinds(): string[] {
  232. if (!this._geometry) {
  233. var result = [];
  234. if (this._delayInfo) {
  235. for (var kind in this._delayInfo) {
  236. result.push(kind);
  237. }
  238. }
  239. return result;
  240. }
  241. return this._geometry.getVerticesDataKinds();
  242. }
  243. public getTotalIndices(): number {
  244. if (!this._geometry) {
  245. return 0;
  246. }
  247. return this._geometry.getTotalIndices();
  248. }
  249. public getIndices(copyWhenShared?: boolean): number[] {
  250. if (!this._geometry) {
  251. return [];
  252. }
  253. return this._geometry.getIndices(copyWhenShared);
  254. }
  255. public get isBlocked(): boolean {
  256. return this._masterMesh !== null && this._masterMesh !== undefined;
  257. }
  258. public isReady(): boolean {
  259. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  260. return false;
  261. }
  262. return super.isReady();
  263. }
  264. public isDisposed(): boolean {
  265. return this._isDisposed;
  266. }
  267. public get sideOrientation(): number {
  268. return this._sideOrientation;
  269. }
  270. public set sideOrientation(sideO: number) {
  271. this._sideOrientation = sideO;
  272. }
  273. public get areNormalsFrozen(): boolean {
  274. return this._areNormalsFrozen;
  275. }
  276. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  277. public freezeNormals(): void {
  278. this._areNormalsFrozen = true;
  279. }
  280. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  281. public unfreezeNormals(): void {
  282. this._areNormalsFrozen = false;
  283. }
  284. // Methods
  285. public _preActivate(): void {
  286. var sceneRenderId = this.getScene().getRenderId();
  287. if (this._preActivateId === sceneRenderId) {
  288. return;
  289. }
  290. this._preActivateId = sceneRenderId;
  291. this._visibleInstances = null;
  292. }
  293. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  294. if (!this._visibleInstances) {
  295. this._visibleInstances = {};
  296. this._visibleInstances.defaultRenderId = renderId;
  297. this._visibleInstances.selfDefaultRenderId = this._renderId;
  298. }
  299. if (!this._visibleInstances[renderId]) {
  300. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  301. }
  302. this._visibleInstances[renderId].push(instance);
  303. }
  304. public refreshBoundingInfo(): void {
  305. var data = this.getVerticesData(VertexBuffer.PositionKind);
  306. if (data) {
  307. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  308. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  309. }
  310. if (this.subMeshes) {
  311. for (var index = 0; index < this.subMeshes.length; index++) {
  312. this.subMeshes[index].refreshBoundingInfo();
  313. }
  314. }
  315. this._updateBoundingInfo();
  316. }
  317. public _createGlobalSubMesh(): SubMesh {
  318. var totalVertices = this.getTotalVertices();
  319. if (!totalVertices || !this.getIndices()) {
  320. return null;
  321. }
  322. this.releaseSubMeshes();
  323. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  324. }
  325. public subdivide(count: number): void {
  326. if (count < 1) {
  327. return;
  328. }
  329. var totalIndices = this.getTotalIndices();
  330. var subdivisionSize = (totalIndices / count) | 0;
  331. var offset = 0;
  332. // Ensure that subdivisionSize is a multiple of 3
  333. while (subdivisionSize % 3 !== 0) {
  334. subdivisionSize++;
  335. }
  336. this.releaseSubMeshes();
  337. for (var index = 0; index < count; index++) {
  338. if (offset >= totalIndices) {
  339. break;
  340. }
  341. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  342. offset += subdivisionSize;
  343. }
  344. this.synchronizeInstances();
  345. }
  346. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  347. if (kind instanceof Array) {
  348. var temp = data;
  349. data = kind;
  350. kind = temp;
  351. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  352. }
  353. if (!this._geometry) {
  354. var vertexData = new VertexData();
  355. vertexData.set(data, kind);
  356. var scene = this.getScene();
  357. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  358. }
  359. else {
  360. this._geometry.setVerticesData(kind, data, updatable, stride);
  361. }
  362. }
  363. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  364. if (!this._geometry) {
  365. return;
  366. }
  367. if (!makeItUnique) {
  368. this._geometry.updateVerticesData(kind, data, updateExtends);
  369. }
  370. else {
  371. this.makeGeometryUnique();
  372. this.updateVerticesData(kind, data, updateExtends, false);
  373. }
  374. }
  375. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  376. if (!this._geometry) {
  377. return;
  378. }
  379. if (!makeItUnique) {
  380. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  381. }
  382. else {
  383. this.makeGeometryUnique();
  384. this.updateVerticesDataDirectly(kind, data, offset, false);
  385. }
  386. }
  387. // Mesh positions update function :
  388. // updates the mesh positions according to the positionFunction returned values.
  389. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  390. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  391. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  392. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  393. positionFunction(positions);
  394. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  395. if (computeNormals) {
  396. var indices = this.getIndices();
  397. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  398. VertexData.ComputeNormals(positions, indices, normals);
  399. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  400. }
  401. }
  402. public makeGeometryUnique() {
  403. if (!this._geometry) {
  404. return;
  405. }
  406. var geometry = this._geometry.copy(Geometry.RandomId());
  407. geometry.applyToMesh(this);
  408. }
  409. public setIndices(indices: number[], totalVertices?: number): void {
  410. if (!this._geometry) {
  411. var vertexData = new VertexData();
  412. vertexData.indices = indices;
  413. var scene = this.getScene();
  414. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  415. }
  416. else {
  417. this._geometry.setIndices(indices, totalVertices);
  418. }
  419. }
  420. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  421. var engine = this.getScene().getEngine();
  422. // Wireframe
  423. var indexToBind;
  424. switch (fillMode) {
  425. case Material.PointFillMode:
  426. indexToBind = null;
  427. break;
  428. case Material.WireFrameFillMode:
  429. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  430. break;
  431. default:
  432. case Material.TriangleFillMode:
  433. indexToBind = this._geometry.getIndexBuffer();
  434. break;
  435. }
  436. // VBOs
  437. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  438. }
  439. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  440. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  441. return;
  442. }
  443. var engine = this.getScene().getEngine();
  444. // Draw order
  445. switch (fillMode) {
  446. case Material.PointFillMode:
  447. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  448. break;
  449. case Material.WireFrameFillMode:
  450. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  451. break;
  452. default:
  453. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  454. }
  455. }
  456. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  457. this._onBeforeRenderCallbacks.push(func);
  458. }
  459. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  460. var index = this._onBeforeRenderCallbacks.indexOf(func);
  461. if (index > -1) {
  462. this._onBeforeRenderCallbacks.splice(index, 1);
  463. }
  464. }
  465. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  466. this._onAfterRenderCallbacks.push(func);
  467. }
  468. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  469. var index = this._onAfterRenderCallbacks.indexOf(func);
  470. if (index > -1) {
  471. this._onAfterRenderCallbacks.splice(index, 1);
  472. }
  473. }
  474. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  475. var scene = this.getScene();
  476. this._batchCache.mustReturn = false;
  477. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  478. this._batchCache.visibleInstances[subMeshId] = null;
  479. if (this._visibleInstances) {
  480. var currentRenderId = scene.getRenderId();
  481. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  482. var selfRenderId = this._renderId;
  483. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  484. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  485. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  486. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  487. }
  488. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  489. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  490. this._batchCache.mustReturn = true;
  491. return this._batchCache;
  492. }
  493. if (currentRenderId !== selfRenderId) {
  494. this._batchCache.renderSelf[subMeshId] = false;
  495. }
  496. }
  497. this._renderIdForInstances[subMeshId] = currentRenderId;
  498. }
  499. return this._batchCache;
  500. }
  501. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  502. var visibleInstances = batch.visibleInstances[subMesh._id];
  503. var matricesCount = visibleInstances.length + 1;
  504. var bufferSize = matricesCount * 16 * 4;
  505. while (this._instancesBufferSize < bufferSize) {
  506. this._instancesBufferSize *= 2;
  507. }
  508. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  509. if (this._worldMatricesInstancesBuffer) {
  510. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  511. }
  512. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  513. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  514. }
  515. var offset = 0;
  516. var instancesCount = 0;
  517. var world = this.getWorldMatrix();
  518. if (batch.renderSelf[subMesh._id]) {
  519. world.copyToArray(this._worldMatricesInstancesArray, offset);
  520. offset += 16;
  521. instancesCount++;
  522. }
  523. if (visibleInstances) {
  524. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  525. var instance = visibleInstances[instanceIndex];
  526. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  527. offset += 16;
  528. instancesCount++;
  529. }
  530. }
  531. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  532. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  533. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  534. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  535. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  536. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  537. this._draw(subMesh, fillMode, instancesCount);
  538. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  539. }
  540. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  541. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  542. var scene = this.getScene();
  543. var engine = scene.getEngine();
  544. if (hardwareInstancedRendering) {
  545. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  546. } else {
  547. if (batch.renderSelf[subMesh._id]) {
  548. // Draw
  549. if (onBeforeDraw) {
  550. onBeforeDraw(false, this.getWorldMatrix());
  551. }
  552. this._draw(subMesh, fillMode);
  553. }
  554. if (batch.visibleInstances[subMesh._id]) {
  555. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  556. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  557. // World
  558. var world = instance.getWorldMatrix();
  559. if (onBeforeDraw) {
  560. onBeforeDraw(true, world);
  561. }
  562. // Draw
  563. this._draw(subMesh, fillMode);
  564. }
  565. }
  566. }
  567. }
  568. public render(subMesh: SubMesh, enableAlphaMode: boolean): void {
  569. var scene = this.getScene();
  570. // Managing instances
  571. var batch = this._getInstancesRenderList(subMesh._id);
  572. if (batch.mustReturn) {
  573. return;
  574. }
  575. // Checking geometry state
  576. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  577. return;
  578. }
  579. var callbackIndex: number;
  580. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  581. this._onBeforeRenderCallbacks[callbackIndex](this);
  582. }
  583. var engine = scene.getEngine();
  584. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  585. // Material
  586. var effectiveMaterial = subMesh.getMaterial();
  587. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  588. return;
  589. }
  590. // Outline - step 1
  591. var savedDepthWrite = engine.getDepthWrite();
  592. if (this.renderOutline) {
  593. engine.setDepthWrite(false);
  594. scene.getOutlineRenderer().render(subMesh, batch);
  595. engine.setDepthWrite(savedDepthWrite);
  596. }
  597. effectiveMaterial._preBind();
  598. var effect = effectiveMaterial.getEffect();
  599. // Bind
  600. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  601. this._bind(subMesh, effect, fillMode);
  602. var world = this.getWorldMatrix();
  603. effectiveMaterial.bind(world, this);
  604. // Alpha mode
  605. if (enableAlphaMode) {
  606. engine.setAlphaMode(effectiveMaterial.alphaMode);
  607. }
  608. // Draw
  609. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  610. (isInstance, world) => {
  611. if (isInstance) {
  612. effectiveMaterial.bindOnlyWorldMatrix(world);
  613. }
  614. });
  615. // Unbind
  616. effectiveMaterial.unbind();
  617. // Outline - step 2
  618. if (this.renderOutline && savedDepthWrite) {
  619. engine.setDepthWrite(true);
  620. engine.setColorWrite(false);
  621. scene.getOutlineRenderer().render(subMesh, batch);
  622. engine.setColorWrite(true);
  623. }
  624. // Overlay
  625. if (this.renderOverlay) {
  626. var currentMode = engine.getAlphaMode();
  627. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  628. scene.getOutlineRenderer().render(subMesh, batch, true);
  629. engine.setAlphaMode(currentMode);
  630. }
  631. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  632. this._onAfterRenderCallbacks[callbackIndex](this);
  633. }
  634. }
  635. public getEmittedParticleSystems(): ParticleSystem[] {
  636. var results = new Array<ParticleSystem>();
  637. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  638. var particleSystem = this.getScene().particleSystems[index];
  639. if (particleSystem.emitter === this) {
  640. results.push(particleSystem);
  641. }
  642. }
  643. return results;
  644. }
  645. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  646. var results = new Array<ParticleSystem>();
  647. var descendants = this.getDescendants();
  648. descendants.push(this);
  649. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  650. var particleSystem = this.getScene().particleSystems[index];
  651. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  652. results.push(particleSystem);
  653. }
  654. }
  655. return results;
  656. }
  657. public getChildren(): Node[] {
  658. var results = [];
  659. for (var index = 0; index < this.getScene().meshes.length; index++) {
  660. var mesh = this.getScene().meshes[index];
  661. if (mesh.parent === this) {
  662. results.push(mesh);
  663. }
  664. }
  665. return results;
  666. }
  667. public _checkDelayState(): void {
  668. var that = this;
  669. var scene = this.getScene();
  670. if (this._geometry) {
  671. this._geometry.load(scene);
  672. }
  673. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  674. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  675. scene._addPendingData(that);
  676. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  677. Tools.LoadFile(this.delayLoadingFile, data => {
  678. if (data instanceof ArrayBuffer) {
  679. this._delayLoadingFunction(data, this);
  680. }
  681. else {
  682. this._delayLoadingFunction(JSON.parse(data), this);
  683. }
  684. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  685. scene._removePendingData(this);
  686. }, () => { }, scene.database, getBinaryData);
  687. }
  688. }
  689. public isInFrustum(frustumPlanes: Plane[]): boolean {
  690. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  691. return false;
  692. }
  693. if (!super.isInFrustum(frustumPlanes)) {
  694. return false;
  695. }
  696. this._checkDelayState();
  697. return true;
  698. }
  699. public setMaterialByID(id: string): void {
  700. var materials = this.getScene().materials;
  701. var index: number;
  702. for (index = 0; index < materials.length; index++) {
  703. if (materials[index].id === id) {
  704. this.material = materials[index];
  705. return;
  706. }
  707. }
  708. // Multi
  709. var multiMaterials = this.getScene().multiMaterials;
  710. for (index = 0; index < multiMaterials.length; index++) {
  711. if (multiMaterials[index].id === id) {
  712. this.material = multiMaterials[index];
  713. return;
  714. }
  715. }
  716. }
  717. public getAnimatables(): IAnimatable[] {
  718. var results = [];
  719. if (this.material) {
  720. results.push(this.material);
  721. }
  722. if (this.skeleton) {
  723. results.push(this.skeleton);
  724. }
  725. return results;
  726. }
  727. // Geometry
  728. public bakeTransformIntoVertices(transform: Matrix): void {
  729. // Position
  730. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  731. return;
  732. }
  733. this._resetPointsArrayCache();
  734. var data = this.getVerticesData(VertexBuffer.PositionKind);
  735. var temp = [];
  736. var index: number;
  737. for (index = 0; index < data.length; index += 3) {
  738. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  739. }
  740. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  741. // Normals
  742. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  743. return;
  744. }
  745. data = this.getVerticesData(VertexBuffer.NormalKind);
  746. temp = [];
  747. for (index = 0; index < data.length; index += 3) {
  748. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  749. }
  750. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  751. // flip faces?
  752. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  753. }
  754. // Will apply current transform to mesh and reset world matrix
  755. public bakeCurrentTransformIntoVertices(): void {
  756. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  757. this.scaling.copyFromFloats(1, 1, 1);
  758. this.position.copyFromFloats(0, 0, 0);
  759. this.rotation.copyFromFloats(0, 0, 0);
  760. //only if quaternion is already set
  761. if (this.rotationQuaternion) {
  762. this.rotationQuaternion = Quaternion.Identity();
  763. }
  764. this._worldMatrix = Matrix.Identity();
  765. }
  766. // Cache
  767. public _resetPointsArrayCache(): void {
  768. this._positions = null;
  769. }
  770. public _generatePointsArray(): boolean {
  771. if (this._positions)
  772. return true;
  773. this._positions = [];
  774. var data = this.getVerticesData(VertexBuffer.PositionKind);
  775. if (!data) {
  776. return false;
  777. }
  778. for (var index = 0; index < data.length; index += 3) {
  779. this._positions.push(Vector3.FromArray(data, index));
  780. }
  781. return true;
  782. }
  783. // Clone
  784. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  785. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  786. }
  787. // Dispose
  788. public dispose(doNotRecurse?: boolean): void {
  789. if (this._geometry) {
  790. this._geometry.releaseForMesh(this, true);
  791. }
  792. // Instances
  793. if (this._worldMatricesInstancesBuffer) {
  794. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  795. this._worldMatricesInstancesBuffer = null;
  796. }
  797. while (this.instances.length) {
  798. this.instances[0].dispose();
  799. }
  800. super.dispose(doNotRecurse);
  801. }
  802. // Geometric tools
  803. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  804. var scene = this.getScene();
  805. var onload = img => {
  806. // Getting height map data
  807. var canvas = document.createElement("canvas");
  808. var context = canvas.getContext("2d");
  809. var heightMapWidth = img.width;
  810. var heightMapHeight = img.height;
  811. canvas.width = heightMapWidth;
  812. canvas.height = heightMapHeight;
  813. context.drawImage(img, 0, 0);
  814. // Create VertexData from map data
  815. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  816. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  817. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  818. //execute success callback, if set
  819. if (onSuccess) {
  820. onSuccess(this);
  821. }
  822. };
  823. Tools.LoadImage(url, onload, () => { }, scene.database);
  824. }
  825. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  826. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  827. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  828. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  829. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  830. return;
  831. }
  832. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  833. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  834. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  835. var position = Vector3.Zero();
  836. var normal = Vector3.Zero();
  837. var uv = Vector2.Zero();
  838. for (var index = 0; index < positions.length; index += 3) {
  839. Vector3.FromArrayToRef(positions, index, position);
  840. Vector3.FromArrayToRef(normals, index, normal);
  841. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  842. // Compute height
  843. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  844. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  845. var pos = (u + v * heightMapWidth) * 4;
  846. var r = buffer[pos] / 255.0;
  847. var g = buffer[pos + 1] / 255.0;
  848. var b = buffer[pos + 2] / 255.0;
  849. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  850. normal.normalize();
  851. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  852. position = position.add(normal);
  853. position.toArray(positions, index);
  854. }
  855. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  856. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  857. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  858. }
  859. public convertToFlatShadedMesh(): void {
  860. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  861. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  862. var kinds = this.getVerticesDataKinds();
  863. var vbs = [];
  864. var data = [];
  865. var newdata = [];
  866. var updatableNormals = false;
  867. var kindIndex: number;
  868. var kind: string;
  869. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  870. kind = kinds[kindIndex];
  871. var vertexBuffer = this.getVertexBuffer(kind);
  872. if (kind === VertexBuffer.NormalKind) {
  873. updatableNormals = vertexBuffer.isUpdatable();
  874. kinds.splice(kindIndex, 1);
  875. kindIndex--;
  876. continue;
  877. }
  878. vbs[kind] = vertexBuffer;
  879. data[kind] = vbs[kind].getData();
  880. newdata[kind] = [];
  881. }
  882. // Save previous submeshes
  883. var previousSubmeshes = this.subMeshes.slice(0);
  884. var indices = this.getIndices();
  885. var totalIndices = this.getTotalIndices();
  886. // Generating unique vertices per face
  887. var index: number;
  888. for (index = 0; index < totalIndices; index++) {
  889. var vertexIndex = indices[index];
  890. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  891. kind = kinds[kindIndex];
  892. var stride = vbs[kind].getStrideSize();
  893. for (var offset = 0; offset < stride; offset++) {
  894. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  895. }
  896. }
  897. }
  898. // Updating faces & normal
  899. var normals = [];
  900. var positions = newdata[VertexBuffer.PositionKind];
  901. for (index = 0; index < totalIndices; index += 3) {
  902. indices[index] = index;
  903. indices[index + 1] = index + 1;
  904. indices[index + 2] = index + 2;
  905. var p1 = Vector3.FromArray(positions, index * 3);
  906. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  907. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  908. var p1p2 = p1.subtract(p2);
  909. var p3p2 = p3.subtract(p2);
  910. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  911. // Store same normals for every vertex
  912. for (var localIndex = 0; localIndex < 3; localIndex++) {
  913. normals.push(normal.x);
  914. normals.push(normal.y);
  915. normals.push(normal.z);
  916. }
  917. }
  918. this.setIndices(indices);
  919. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  920. // Updating vertex buffers
  921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  922. kind = kinds[kindIndex];
  923. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  924. }
  925. // Updating submeshes
  926. this.releaseSubMeshes();
  927. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  928. var previousOne = previousSubmeshes[submeshIndex];
  929. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  930. }
  931. this.synchronizeInstances();
  932. }
  933. // will inverse faces orientations, and invert normals too if specified
  934. public flipFaces(flipNormals: boolean = false): void {
  935. var vertex_data = VertexData.ExtractFromMesh(this);
  936. var i: number;
  937. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  938. for (i = 0; i < vertex_data.normals.length; i++) {
  939. vertex_data.normals[i] *= -1;
  940. }
  941. }
  942. var temp;
  943. for (i = 0; i < vertex_data.indices.length; i += 3) {
  944. // reassign indices
  945. temp = vertex_data.indices[i + 1];
  946. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  947. vertex_data.indices[i + 2] = temp;
  948. }
  949. vertex_data.applyToMesh(this);
  950. }
  951. // Instances
  952. public createInstance(name: string): InstancedMesh {
  953. return new InstancedMesh(name, this);
  954. }
  955. public synchronizeInstances(): void {
  956. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  957. var instance = this.instances[instanceIndex];
  958. instance._syncSubMeshes();
  959. }
  960. }
  961. /**
  962. * Simplify the mesh according to the given array of settings.
  963. * Function will return immediately and will simplify async.
  964. * @param settings a collection of simplification settings.
  965. * @param parallelProcessing should all levels calculate parallel or one after the other.
  966. * @param type the type of simplification to run.
  967. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  968. */
  969. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  970. this.getScene().simplificationQueue.addTask({
  971. settings: settings,
  972. parallelProcessing: parallelProcessing,
  973. mesh: this,
  974. simplificationType: simplificationType,
  975. successCallback: successCallback
  976. });
  977. }
  978. /**
  979. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  980. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  981. * This should be used together with the simplification to avoid disappearing triangles.
  982. * @param successCallback an optional success callback to be called after the optimization finished.
  983. */
  984. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  985. var indices = this.getIndices();
  986. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  987. var vectorPositions = [];
  988. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  989. vectorPositions.push(Vector3.FromArray(positions, pos));
  990. }
  991. var dupes = [];
  992. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  993. var realPos = vectorPositions.length - 1 - iteration;
  994. var testedPosition = vectorPositions[realPos];
  995. for (var j = 0; j < realPos; ++j) {
  996. var againstPosition = vectorPositions[j];
  997. if (testedPosition.equals(againstPosition)) {
  998. dupes[realPos] = j;
  999. break;
  1000. }
  1001. }
  1002. }, () => {
  1003. for (var i = 0; i < indices.length; ++i) {
  1004. indices[i] = dupes[indices[i]] || indices[i];
  1005. }
  1006. //indices are now reordered
  1007. var originalSubMeshes = this.subMeshes.slice(0);
  1008. this.setIndices(indices);
  1009. this.subMeshes = originalSubMeshes;
  1010. if (successCallback) {
  1011. successCallback(this);
  1012. }
  1013. });
  1014. }
  1015. // Statics
  1016. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, ribbonInstance: Mesh = null): Mesh {
  1017. if (ribbonInstance) { // existing ribbon instance update
  1018. // positionFunction : ribbon case
  1019. // only pathArray and sideOrientation parameters are taken into account for positions update
  1020. var positionFunction = positions => {
  1021. var minlg = pathArray[0].length;
  1022. var i = 0;
  1023. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  1024. for (var si = 1; si <= ns; si++) {
  1025. for (var p = 0; p < pathArray.length; p++) {
  1026. var path = pathArray[p];
  1027. var l = path.length;
  1028. minlg = (minlg < l) ? minlg : l;
  1029. var j = 0;
  1030. while (j < minlg) {
  1031. positions[i] = path[j].x;
  1032. positions[i + 1] = path[j].y;
  1033. positions[i + 2] = path[j].z;
  1034. j++;
  1035. i += 3;
  1036. }
  1037. if ((<any>ribbonInstance)._closePath) {
  1038. positions[i] = path[0].x;
  1039. positions[i + 1] = path[0].y;
  1040. positions[i + 2] = path[0].z;
  1041. i += 3;
  1042. }
  1043. }
  1044. }
  1045. };
  1046. var positions = ribbonInstance.getVerticesData(VertexBuffer.PositionKind);
  1047. positionFunction(positions);
  1048. ribbonInstance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  1049. if (!(ribbonInstance.areNormalsFrozen)) {
  1050. var indices = ribbonInstance.getIndices();
  1051. var normals = ribbonInstance.getVerticesData(VertexBuffer.NormalKind);
  1052. VertexData.ComputeNormals(positions, indices, normals);
  1053. if ((<any>ribbonInstance)._closePath) {
  1054. var indexFirst: number = 0;
  1055. var indexLast: number = 0;
  1056. for (var p = 0; p < pathArray.length; p++) {
  1057. indexFirst = (<any>ribbonInstance)._idx[p] * 3;
  1058. if (p + 1 < pathArray.length) {
  1059. indexLast = ((<any>ribbonInstance)._idx[p + 1] - 1) * 3;
  1060. }
  1061. else {
  1062. indexLast = normals.length - 3;
  1063. }
  1064. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  1065. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  1066. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  1067. normals[indexLast] = normals[indexFirst];
  1068. normals[indexLast + 1] = normals[indexFirst + 1];
  1069. normals[indexLast + 2] = normals[indexFirst + 2];
  1070. }
  1071. }
  1072. ribbonInstance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  1073. }
  1074. return ribbonInstance;
  1075. }
  1076. else { // new ribbon creation
  1077. var ribbon = new Mesh(name, scene);
  1078. ribbon.sideOrientation = sideOrientation;
  1079. var vertexData = VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  1080. if (closePath) {
  1081. (<any>ribbon)._idx = (<any>vertexData)._idx;
  1082. }
  1083. (<any>ribbon)._closePath = closePath;
  1084. vertexData.applyToMesh(ribbon, updatable);
  1085. return ribbon;
  1086. }
  1087. }
  1088. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1089. var disc = new Mesh(name, scene);
  1090. var vertexData = VertexData.CreateDisc(radius, tessellation, sideOrientation);
  1091. vertexData.applyToMesh(disc, updatable);
  1092. return disc;
  1093. }
  1094. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1095. public static CreateBox(name: string, options: { width?: number, height?: number, depth?: number, faceUV?: Vector4[], faceColors?: Color4[], sideOrientation?: number, updatable?: boolean}, scene: Scene): Mesh;
  1096. public static CreateBox(name: string, options: any, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1097. // Check parameters
  1098. updatable = updatable || options.updatable;
  1099. var box = new Mesh(name, scene);
  1100. var vertexData = VertexData.CreateBox(options, sideOrientation);
  1101. vertexData.applyToMesh(box, updatable);
  1102. return box;
  1103. }
  1104. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1105. public static CreateSphere(name: string, options: { segments?: number, diameterX?: number, diameterY?: number, diameterZ?: number, sideOrientation?: number, updatable?: boolean}, scene: any): Mesh;
  1106. public static CreateSphere(name: string, options: any, diameterOrScene: any, scene?: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1107. if (diameterOrScene instanceof Scene) {
  1108. scene = diameterOrScene;
  1109. updatable = options.updatable;
  1110. } else {
  1111. var segments = options;
  1112. options = {
  1113. segments: segments,
  1114. diameterX: diameterOrScene,
  1115. diameterY: diameterOrScene,
  1116. diameterZ: diameterOrScene,
  1117. sideOrientation: sideOrientation
  1118. }
  1119. }
  1120. var sphere = new Mesh(name, scene);
  1121. var vertexData = VertexData.CreateSphere(options);
  1122. vertexData.applyToMesh(sphere, updatable);
  1123. return sphere;
  1124. }
  1125. // Cylinder and cone
  1126. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1127. // subdivisions is a new parameter, we need to support old signature
  1128. if (scene === undefined || !(scene instanceof Scene)) {
  1129. if (scene !== undefined) {
  1130. updatable = scene;
  1131. }
  1132. scene = <Scene>subdivisions;
  1133. subdivisions = 1;
  1134. }
  1135. var cylinder = new Mesh(name, scene);
  1136. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  1137. vertexData.applyToMesh(cylinder, updatable);
  1138. return cylinder;
  1139. }
  1140. // Torus (Code from SharpDX.org)
  1141. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1142. var torus = new Mesh(name, scene);
  1143. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  1144. vertexData.applyToMesh(torus, updatable);
  1145. return torus;
  1146. }
  1147. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1148. var torusKnot = new Mesh(name, scene);
  1149. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  1150. vertexData.applyToMesh(torusKnot, updatable);
  1151. return torusKnot;
  1152. }
  1153. // Lines
  1154. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, linesInstance: LinesMesh = null): LinesMesh {
  1155. if (linesInstance) { // lines update
  1156. var positionFunction = positions => {
  1157. var i = 0;
  1158. for (var p = 0; p < points.length; p++) {
  1159. positions[i] = points[p].x;
  1160. positions[i + 1] = points[p].y;
  1161. positions[i + 2] = points[p].z;
  1162. i += 3;
  1163. }
  1164. };
  1165. linesInstance.updateMeshPositions(positionFunction, false);
  1166. return linesInstance;
  1167. }
  1168. // lines creation
  1169. var lines = new LinesMesh(name, scene, updatable);
  1170. var vertexData = VertexData.CreateLines(points);
  1171. vertexData.applyToMesh(lines, updatable);
  1172. return lines;
  1173. }
  1174. // Dashed Lines
  1175. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, linesInstance: LinesMesh = null): LinesMesh {
  1176. if (linesInstance) { // dashed lines update
  1177. var positionFunction = (positions: number[]): void => {
  1178. var curvect = Vector3.Zero();
  1179. var nbSeg = positions.length / 6;
  1180. var lg = 0;
  1181. var nb = 0;
  1182. var shft = 0;
  1183. var dashshft = 0;
  1184. var curshft = 0;
  1185. var p = 0;
  1186. var i = 0;
  1187. var j = 0;
  1188. for (i = 0; i < points.length - 1; i++) {
  1189. points[i + 1].subtractToRef(points[i], curvect);
  1190. lg += curvect.length();
  1191. }
  1192. shft = lg / nbSeg;
  1193. dashshft = (<any>linesInstance).dashSize * shft / ((<any>linesInstance).dashSize + (<any>linesInstance).gapSize);
  1194. for (i = 0; i < points.length - 1; i++) {
  1195. points[i + 1].subtractToRef(points[i], curvect);
  1196. nb = Math.floor(curvect.length() / shft);
  1197. curvect.normalize();
  1198. j = 0;
  1199. while (j < nb && p < positions.length) {
  1200. curshft = shft * j;
  1201. positions[p] = points[i].x + curshft * curvect.x;
  1202. positions[p + 1] = points[i].y + curshft * curvect.y;
  1203. positions[p + 2] = points[i].z + curshft * curvect.z;
  1204. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  1205. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  1206. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  1207. p += 6;
  1208. j++;
  1209. }
  1210. }
  1211. while (p < positions.length) {
  1212. positions[p] = points[i].x;
  1213. positions[p + 1] = points[i].y;
  1214. positions[p + 2] = points[i].z;
  1215. p += 3;
  1216. }
  1217. };
  1218. linesInstance.updateMeshPositions(positionFunction, false);
  1219. return linesInstance;
  1220. }
  1221. // dashed lines creation
  1222. var dashedLines = new LinesMesh(name, scene, updatable);
  1223. var vertexData = VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  1224. vertexData.applyToMesh(dashedLines, updatable);
  1225. (<any>dashedLines).dashSize = dashSize;
  1226. (<any>dashedLines).gapSize = gapSize;
  1227. return dashedLines;
  1228. }
  1229. // Extrusion
  1230. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1231. scale = scale || 1;
  1232. rotation = rotation || 0;
  1233. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  1234. return extruded;
  1235. }
  1236. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1237. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  1238. return extrudedCustom;
  1239. }
  1240. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: number, rotation: number, scaleFunction: { (i: number, distance: number): number; }, rotateFunction: { (i: number, distance: number): number; }, rbCA: boolean, rbCP: boolean, cap: number, custom: boolean, scene: Scene, updtbl: boolean, side: number, instance: Mesh): Mesh {
  1241. // extrusion geometry
  1242. var extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) => {
  1243. var tangents = path3D.getTangents();
  1244. var normals = path3D.getNormals();
  1245. var binormals = path3D.getBinormals();
  1246. var distances = path3D.getDistances();
  1247. var angle = 0;
  1248. var returnScale: { (i: number, distance: number): number; } = (i, distance) => { return scale; };
  1249. var returnRotation: { (i: number, distance: number): number; } = (i, distance) => { return rotation; };
  1250. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  1251. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  1252. var index = 0;
  1253. for (var i = 0; i < curve.length; i++) {
  1254. var shapePath = new Array<Vector3>();
  1255. var angleStep = rotate(i, distances[i]);
  1256. var scaleRatio = scl(i, distances[i]);
  1257. for (var p = 0; p < shape.length; p++) {
  1258. var rotationMatrix = Matrix.RotationAxis(tangents[i], angle);
  1259. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1260. var rotated = Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1261. shapePath.push(rotated);
  1262. }
  1263. shapePaths[index] = shapePath;
  1264. angle += angleStep;
  1265. index++;
  1266. }
  1267. // cap
  1268. var capPath = shapePath => {
  1269. var pointCap = Array<Vector3>();
  1270. var barycenter = Vector3.Zero();
  1271. var i: number;
  1272. for (i = 0; i < shapePath.length; i++) {
  1273. barycenter.addInPlace(shapePath[i]);
  1274. }
  1275. barycenter.scaleInPlace(1 / shapePath.length);
  1276. for (i = 0; i < shapePath.length; i++) {
  1277. pointCap.push(barycenter);
  1278. }
  1279. return pointCap;
  1280. };
  1281. switch (cap) {
  1282. case Mesh.NO_CAP:
  1283. break;
  1284. case Mesh.CAP_START:
  1285. shapePaths.unshift(capPath(shapePaths[0]));
  1286. break;
  1287. case Mesh.CAP_END:
  1288. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1289. break;
  1290. case Mesh.CAP_ALL:
  1291. shapePaths.unshift(capPath(shapePaths[0]));
  1292. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1293. break;
  1294. default:
  1295. break;
  1296. }
  1297. return shapePaths;
  1298. };
  1299. var path3D;
  1300. var pathArray;
  1301. if (instance) { // instance update
  1302. path3D = ((<any>instance).path3D).update(curve);
  1303. pathArray = extrusionPathArray(shape, curve, (<any>instance).path3D, (<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction, (<any>instance).cap, custom);
  1304. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1305. return instance;
  1306. }
  1307. // extruded shape creation
  1308. path3D = <any>new Path3D(curve);
  1309. var newShapePaths = new Array<Array<Vector3>>();
  1310. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1311. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1312. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1313. (<any>extrudedGeneric).pathArray = pathArray;
  1314. (<any>extrudedGeneric).path3D = path3D;
  1315. (<any>extrudedGeneric).cap = cap;
  1316. return extrudedGeneric;
  1317. }
  1318. // Lathe
  1319. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1320. radius = radius || 1;
  1321. tessellation = tessellation || radius * 60;
  1322. var pi2 = Math.PI * 2;
  1323. var shapeLathe = new Array<Vector3>();
  1324. // first rotatable point
  1325. var i = 0;
  1326. while (shape[i].x === 0) {
  1327. i++;
  1328. }
  1329. var pt = shape[i];
  1330. for (i = 0; i < shape.length; i++) {
  1331. shapeLathe.push(shape[i].subtract(pt));
  1332. }
  1333. // circle path
  1334. var step = pi2 / tessellation;
  1335. var rotated;
  1336. var path = new Array<Vector3>();;
  1337. for (i = 0; i < tessellation; i++) {
  1338. rotated = new Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  1339. path.push(rotated);
  1340. }
  1341. path.push(path[0]);
  1342. // extrusion
  1343. var scaleFunction = () => { return 1; };
  1344. var rotateFunction = () => { return 0; };
  1345. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  1346. return lathe;
  1347. }
  1348. // Plane & ground
  1349. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
  1350. public static CreatePlane(name: string, options: { width?: number, height?: number, sideOrientation?: number, updatable?: boolean}, scene: Scene): Mesh;
  1351. public static CreatePlane(name: string, options: any, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1352. var plane = new Mesh(name, scene);
  1353. var vertexData = VertexData.CreatePlane(options, sideOrientation);
  1354. vertexData.applyToMesh(plane, updatable || options.updatable);
  1355. return plane;
  1356. }
  1357. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh;
  1358. public static CreateGround(name: string, options: { width?: number, height?: number, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: any): Mesh;
  1359. public static CreateGround(name: string, options: any, heightOrScene: any, subdivisions?: number, scene?: Scene, updatable?: boolean): Mesh {
  1360. if (heightOrScene instanceof Scene) {
  1361. scene = heightOrScene;
  1362. updatable = options.updatable;
  1363. } else {
  1364. var width = options;
  1365. options = {
  1366. width: width,
  1367. height: heightOrScene,
  1368. subdivisions: subdivisions
  1369. }
  1370. }
  1371. var ground = new GroundMesh(name, scene);
  1372. ground._setReady(false);
  1373. ground._subdivisions = options.subdivisions || 1;
  1374. var vertexData = VertexData.CreateGround(options);
  1375. vertexData.applyToMesh(ground, updatable || options.updatable);
  1376. ground._setReady(true);
  1377. return ground;
  1378. }
  1379. 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 {
  1380. var tiledGround = new Mesh(name, scene);
  1381. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1382. vertexData.applyToMesh(tiledGround, updatable);
  1383. return tiledGround;
  1384. }
  1385. 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 {
  1386. var ground = new GroundMesh(name, scene);
  1387. ground._subdivisions = subdivisions;
  1388. ground._setReady(false);
  1389. var onload = img => {
  1390. // Getting height map data
  1391. var canvas = document.createElement("canvas");
  1392. var context = canvas.getContext("2d");
  1393. var heightMapWidth = img.width;
  1394. var heightMapHeight = img.height;
  1395. canvas.width = heightMapWidth;
  1396. canvas.height = heightMapHeight;
  1397. context.drawImage(img, 0, 0);
  1398. // Create VertexData from map data
  1399. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1400. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1401. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1402. vertexData.applyToMesh(ground, updatable);
  1403. ground._setReady(true);
  1404. //execute ready callback, if set
  1405. if (onReady) {
  1406. onReady(ground);
  1407. }
  1408. };
  1409. Tools.LoadImage(url, onload, () => { }, scene.database);
  1410. return ground;
  1411. }
  1412. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, tubeInstance: Mesh = null): Mesh {
  1413. // tube geometry
  1414. var tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) => {
  1415. var tangents = path3D.getTangents();
  1416. var normals = path3D.getNormals();
  1417. var distances = path3D.getDistances();
  1418. var pi2 = Math.PI * 2;
  1419. var step = pi2 / tessellation;
  1420. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  1421. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  1422. var circlePath: Vector3[];
  1423. var rad: number;
  1424. var normal: Vector3;
  1425. var rotated: Vector3;
  1426. var rotationMatrix: Matrix;
  1427. var index = 0;
  1428. for (var i = 0; i < path.length; i++) {
  1429. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1430. circlePath = Array<Vector3>(); // current circle array
  1431. normal = normals[i]; // current normal
  1432. for (var t = 0; t < tessellation; t++) {
  1433. rotationMatrix = Matrix.RotationAxis(tangents[i], step * t);
  1434. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1435. circlePath.push(rotated);
  1436. }
  1437. circlePaths[index] = circlePath;
  1438. index++;
  1439. }
  1440. // cap
  1441. var capPath = function (nbPoints, pathIndex) {
  1442. var pointCap = Array<Vector3>();
  1443. for (var i = 0; i < nbPoints; i++) {
  1444. pointCap.push(path[pathIndex]);
  1445. }
  1446. return pointCap;
  1447. };
  1448. switch (cap) {
  1449. case Mesh.NO_CAP:
  1450. break;
  1451. case Mesh.CAP_START:
  1452. circlePaths.unshift(capPath(tessellation + 1, 0));
  1453. break;
  1454. case Mesh.CAP_END:
  1455. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1456. break;
  1457. case Mesh.CAP_ALL:
  1458. circlePaths.unshift(capPath(tessellation + 1, 0));
  1459. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1460. break;
  1461. default:
  1462. break;
  1463. }
  1464. return circlePaths;
  1465. };
  1466. var path3D;
  1467. var pathArray;
  1468. if (tubeInstance) { // tube update
  1469. path3D = ((<any>tubeInstance).path3D).update(path);
  1470. pathArray = tubePathArray(path, path3D, (<any>tubeInstance).pathArray, radius, (<any>tubeInstance).tessellation, radiusFunction, (<any>tubeInstance).cap);
  1471. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  1472. return tubeInstance;
  1473. }
  1474. // tube creation
  1475. path3D = <any>new Path3D(path);
  1476. var newPathArray = new Array<Array<Vector3>>();
  1477. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1478. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  1479. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  1480. (<any>tube).pathArray = pathArray;
  1481. (<any>tube).path3D = path3D;
  1482. (<any>tube).tessellation = tessellation;
  1483. (<any>tube).cap = cap;
  1484. return tube;
  1485. }
  1486. // Decals
  1487. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number = 0) {
  1488. var indices = sourceMesh.getIndices();
  1489. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  1490. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  1491. // Getting correct rotation
  1492. if (!normal) {
  1493. var target = new Vector3(0, 0, 1);
  1494. var camera = sourceMesh.getScene().activeCamera;
  1495. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1496. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1497. }
  1498. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1499. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1500. var pitch = Math.atan2(normal.y, len);
  1501. // Matrix
  1502. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  1503. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  1504. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1505. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1506. var vertexData = new VertexData();
  1507. vertexData.indices = [];
  1508. vertexData.positions = [];
  1509. vertexData.normals = [];
  1510. vertexData.uvs = [];
  1511. var currentVertexDataIndex = 0;
  1512. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  1513. var vertexId = indices[indexId];
  1514. var result = new PositionNormalVertex();
  1515. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1516. // Send vector to decal local world
  1517. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  1518. // Get normal
  1519. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1520. return result;
  1521. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1522. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  1523. if (vertices.length === 0) {
  1524. return vertices;
  1525. }
  1526. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  1527. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  1528. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1529. return new PositionNormalVertex(
  1530. Vector3.Lerp(v0.position, v1.position, clipFactor),
  1531. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  1532. );
  1533. };
  1534. var result = new Array<PositionNormalVertex>();
  1535. for (var index = 0; index < vertices.length; index += 3) {
  1536. var v1Out: boolean;
  1537. var v2Out: boolean;
  1538. var v3Out: boolean;
  1539. var total = 0;
  1540. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  1541. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  1542. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1543. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1544. v1Out = d1 > 0;
  1545. v2Out = d2 > 0;
  1546. v3Out = d3 > 0;
  1547. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1548. switch (total) {
  1549. case 0:
  1550. result.push(vertices[index]);
  1551. result.push(vertices[index + 1]);
  1552. result.push(vertices[index + 2]);
  1553. break;
  1554. case 1:
  1555. if (v1Out) {
  1556. nV1 = vertices[index + 1];
  1557. nV2 = vertices[index + 2];
  1558. nV3 = clipVertices(vertices[index], nV1);
  1559. nV4 = clipVertices(vertices[index], nV2);
  1560. }
  1561. if (v2Out) {
  1562. nV1 = vertices[index];
  1563. nV2 = vertices[index + 2];
  1564. nV3 = clipVertices(vertices[index + 1], nV1);
  1565. nV4 = clipVertices(vertices[index + 1], nV2);
  1566. result.push(nV3);
  1567. result.push(nV2.clone());
  1568. result.push(nV1.clone());
  1569. result.push(nV2.clone());
  1570. result.push(nV3.clone());
  1571. result.push(nV4);
  1572. break;
  1573. }
  1574. if (v3Out) {
  1575. nV1 = vertices[index];
  1576. nV2 = vertices[index + 1];
  1577. nV3 = clipVertices(vertices[index + 2], nV1);
  1578. nV4 = clipVertices(vertices[index + 2], nV2);
  1579. }
  1580. result.push(nV1.clone());
  1581. result.push(nV2.clone());
  1582. result.push(nV3);
  1583. result.push(nV4);
  1584. result.push(nV3.clone());
  1585. result.push(nV2.clone());
  1586. break;
  1587. case 2:
  1588. if (!v1Out) {
  1589. nV1 = vertices[index].clone();
  1590. nV2 = clipVertices(nV1, vertices[index + 1]);
  1591. nV3 = clipVertices(nV1, vertices[index + 2]);
  1592. result.push(nV1);
  1593. result.push(nV2);
  1594. result.push(nV3);
  1595. }
  1596. if (!v2Out) {
  1597. nV1 = vertices[index + 1].clone();
  1598. nV2 = clipVertices(nV1, vertices[index + 2]);
  1599. nV3 = clipVertices(nV1, vertices[index]);
  1600. result.push(nV1);
  1601. result.push(nV2);
  1602. result.push(nV3);
  1603. }
  1604. if (!v3Out) {
  1605. nV1 = vertices[index + 2].clone();
  1606. nV2 = clipVertices(nV1, vertices[index]);
  1607. nV3 = clipVertices(nV1, vertices[index + 1]);
  1608. result.push(nV1);
  1609. result.push(nV2);
  1610. result.push(nV3);
  1611. }
  1612. break;
  1613. case 3:
  1614. break;
  1615. }
  1616. }
  1617. return result;
  1618. };
  1619. for (var index = 0; index < indices.length; index += 3) {
  1620. var faceVertices = new Array<PositionNormalVertex>();
  1621. faceVertices.push(extractDecalVector3(index));
  1622. faceVertices.push(extractDecalVector3(index + 1));
  1623. faceVertices.push(extractDecalVector3(index + 2));
  1624. // Clip
  1625. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1626. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1627. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1628. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1629. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1630. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1631. if (faceVertices.length === 0) {
  1632. continue;
  1633. }
  1634. // Add UVs and get back to world
  1635. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1636. var vertex = faceVertices[vIndex];
  1637. vertexData.indices.push(currentVertexDataIndex);
  1638. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1639. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1640. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1641. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1642. currentVertexDataIndex++;
  1643. }
  1644. }
  1645. // Return mesh
  1646. var decal = new Mesh(name, sourceMesh.getScene());
  1647. vertexData.applyToMesh(decal);
  1648. decal.position = position.clone();
  1649. decal.rotation = new Vector3(pitch, yaw, angle);
  1650. return decal;
  1651. }
  1652. // Skeletons
  1653. /**
  1654. * Update the vertex buffers by applying transformation from the bones
  1655. * @param {skeleton} skeleton to apply
  1656. */
  1657. public applySkeleton(skeleton: Skeleton): Mesh {
  1658. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1659. return this;
  1660. }
  1661. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1662. return this;
  1663. }
  1664. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  1665. return this;
  1666. }
  1667. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  1668. return this;
  1669. }
  1670. var source: number[];
  1671. if (!this._sourcePositions) {
  1672. source = this.getVerticesData(VertexBuffer.PositionKind);
  1673. this._sourcePositions = new Float32Array(source);
  1674. if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
  1675. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  1676. }
  1677. }
  1678. if (!this._sourceNormals) {
  1679. source = this.getVerticesData(VertexBuffer.NormalKind);
  1680. this._sourceNormals = new Float32Array(source);
  1681. if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
  1682. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  1683. }
  1684. }
  1685. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  1686. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  1687. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  1688. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  1689. var skeletonMatrices = skeleton.getTransformMatrices();
  1690. var tempVector3 = Vector3.Zero();
  1691. var finalMatrix = new Matrix();
  1692. var tempMatrix = new Matrix();
  1693. for (var index = 0; index < positionsData.length; index += 3) {
  1694. var index4 = (index / 3) * 4;
  1695. var matricesWeight0 = matricesWeightsData[index4];
  1696. var matricesWeight1 = matricesWeightsData[index4 + 1];
  1697. var matricesWeight2 = matricesWeightsData[index4 + 2];
  1698. var matricesWeight3 = matricesWeightsData[index4 + 3];
  1699. if (matricesWeight0 > 0) {
  1700. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  1701. finalMatrix.addToSelf(tempMatrix);
  1702. }
  1703. if (matricesWeight1> 0) {
  1704. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  1705. finalMatrix.addToSelf(tempMatrix);
  1706. }
  1707. if (matricesWeight2 > 0) {
  1708. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  1709. finalMatrix.addToSelf(tempMatrix);
  1710. }
  1711. if (matricesWeight3 > 0) {
  1712. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  1713. finalMatrix.addToSelf(tempMatrix);
  1714. }
  1715. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  1716. tempVector3.toArray(positionsData, index);
  1717. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  1718. tempVector3.toArray(normalsData, index);
  1719. finalMatrix.reset();
  1720. }
  1721. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  1722. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  1723. return this;
  1724. }
  1725. // Tools
  1726. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1727. var minVector: Vector3 = null;
  1728. var maxVector: Vector3 = null;
  1729. for (var i in meshes) {
  1730. var mesh = meshes[i];
  1731. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1732. if (!minVector) {
  1733. minVector = boundingBox.minimumWorld;
  1734. maxVector = boundingBox.maximumWorld;
  1735. continue;
  1736. }
  1737. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1738. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1739. }
  1740. return {
  1741. min: minVector,
  1742. max: maxVector
  1743. };
  1744. }
  1745. public static Center(meshesOrMinMaxVector): Vector3 {
  1746. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1747. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1748. }
  1749. /**
  1750. * Merge the array of meshes into a single mesh for performance reasons.
  1751. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1752. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1753. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1754. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1755. */
  1756. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  1757. var index: number;
  1758. if (!allow32BitsIndices) {
  1759. var totalVertices = 0;
  1760. // Counting vertices
  1761. for (index = 0; index < meshes.length; index++) {
  1762. if (meshes[index]) {
  1763. totalVertices += meshes[index].getTotalVertices();
  1764. if (totalVertices > 65536) {
  1765. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1766. return null;
  1767. }
  1768. }
  1769. }
  1770. }
  1771. // Merge
  1772. var vertexData: VertexData;
  1773. var otherVertexData: VertexData;
  1774. var source: Mesh;
  1775. for (index = 0; index < meshes.length; index++) {
  1776. if (meshes[index]) {
  1777. meshes[index].computeWorldMatrix(true);
  1778. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  1779. otherVertexData.transform(meshes[index].getWorldMatrix());
  1780. if (vertexData) {
  1781. vertexData.merge(otherVertexData);
  1782. } else {
  1783. vertexData = otherVertexData;
  1784. source = meshes[index];
  1785. }
  1786. }
  1787. }
  1788. if (!meshSubclass) {
  1789. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1790. }
  1791. vertexData.applyToMesh(meshSubclass);
  1792. // Setting properties
  1793. meshSubclass.material = source.material;
  1794. meshSubclass.checkCollisions = source.checkCollisions;
  1795. // Cleaning
  1796. if (disposeSource) {
  1797. for (index = 0; index < meshes.length; index++) {
  1798. if (meshes[index]) {
  1799. meshes[index].dispose();
  1800. }
  1801. }
  1802. }
  1803. return meshSubclass;
  1804. }
  1805. }
  1806. }