babylon.mesh.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. "use strict";
  2. var BABYLON = BABYLON || {};
  3. (function () {
  4. BABYLON.Mesh = function (name, scene) {
  5. BABYLON.Node.call(this, scene);
  6. this.name = name;
  7. this.id = name;
  8. this._totalVertices = 0;
  9. this._worldMatrix = BABYLON.Matrix.Identity();
  10. scene.meshes.push(this);
  11. this.position = new BABYLON.Vector3(0, 0, 0);
  12. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13. this.rotationQuaternion = null;
  14. this.scaling = new BABYLON.Vector3(1, 1, 1);
  15. this._pivotMatrix = BABYLON.Matrix.Identity();
  16. this._indices = [];
  17. this.subMeshes = [];
  18. this._renderId = 0;
  19. this._onBeforeRenderCallbacks = [];
  20. // Animations
  21. this.animations = [];
  22. // Cache
  23. this._positions = null;
  24. BABYLON.Mesh.prototype._initCache.call(this);
  25. this._localScaling = BABYLON.Matrix.Zero();
  26. this._localRotation = BABYLON.Matrix.Zero();
  27. this._localTranslation = BABYLON.Matrix.Zero();
  28. this._localBillboard = BABYLON.Matrix.Zero();
  29. this._localPivotScaling = BABYLON.Matrix.Zero();
  30. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  31. this._localWorld = BABYLON.Matrix.Zero();
  32. this._worldMatrix = BABYLON.Matrix.Zero();
  33. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  34. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  35. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  36. this._absolutePosition = BABYLON.Vector3.Zero();
  37. };
  38. BABYLON.Mesh.prototype = Object.create(BABYLON.Node.prototype);
  39. // Constants
  40. BABYLON.Mesh.BILLBOARDMODE_NONE = 0;
  41. BABYLON.Mesh.BILLBOARDMODE_X = 1;
  42. BABYLON.Mesh.BILLBOARDMODE_Y = 2;
  43. BABYLON.Mesh.BILLBOARDMODE_Z = 4;
  44. BABYLON.Mesh.BILLBOARDMODE_ALL = 7;
  45. // Members
  46. BABYLON.Mesh.prototype.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  47. BABYLON.Mesh.prototype.material = null;
  48. BABYLON.Mesh.prototype.isVisible = true;
  49. BABYLON.Mesh.prototype.isPickable = true;
  50. BABYLON.Mesh.prototype.visibility = 1.0;
  51. BABYLON.Mesh.prototype.billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  52. BABYLON.Mesh.prototype.checkCollisions = false;
  53. BABYLON.Mesh.prototype.receiveShadows = false;
  54. BABYLON.Mesh.prototype._isDisposed = false;
  55. BABYLON.Mesh.prototype.onDispose = null;
  56. BABYLON.Mesh.prototype.skeleton = null;
  57. BABYLON.Mesh.prototype.renderingGroupId = 0;
  58. BABYLON.Mesh.prototype.infiniteDistance = false;
  59. // Properties
  60. BABYLON.Mesh.prototype.getBoundingInfo = function () {
  61. return this._boundingInfo;
  62. };
  63. BABYLON.Mesh.prototype.getScene = function () {
  64. return this._scene;
  65. };
  66. BABYLON.Mesh.prototype.getWorldMatrix = function () {
  67. if (this._currentRenderId !== this._scene.getRenderId()) {
  68. this.computeWorldMatrix();
  69. }
  70. return this._worldMatrix;
  71. };
  72. BABYLON.Mesh.prototype.getAbsolutePosition = function () {
  73. this.computeWorldMatrix();
  74. return this._absolutePosition;
  75. };
  76. BABYLON.Mesh.prototype.setAbsolutePosition = function (absolutePosition) {
  77. if (!absolutePosition) {
  78. return;
  79. }
  80. var absolutePositionX;
  81. var absolutePositionY;
  82. var absolutePositionZ;
  83. if (absolutePosition.x === undefined) {
  84. if (arguments.length < 3) {
  85. return;
  86. }
  87. absolutePositionX = arguments[0];
  88. absolutePositionY = arguments[1];
  89. absolutePositionZ = arguments[2];
  90. }
  91. else {
  92. absolutePositionX = absolutePosition.x;
  93. absolutePositionY = absolutePosition.y;
  94. absolutePositionZ = absolutePosition.z;
  95. }
  96. // worldMatrix = pivotMatrix * scalingMatrix * rotationMatrix * translateMatrix * parentWorldMatrix
  97. // => translateMatrix = invertRotationMatrix * invertScalingMatrix * invertPivotMatrix * worldMatrix * invertParentWorldMatrix
  98. // get this matrice before the other ones since
  99. // that will update them if they have to be updated
  100. var worldMatrix = this.getWorldMatrix().clone();
  101. worldMatrix.m[12] = absolutePositionX;
  102. worldMatrix.m[13] = absolutePositionY;
  103. worldMatrix.m[14] = absolutePositionZ;
  104. var invertRotationMatrix = this._localRotation.clone();
  105. invertRotationMatrix.invert();
  106. var invertScalingMatrix = this._localScaling.clone();
  107. invertScalingMatrix.invert();
  108. var invertPivotMatrix = this._pivotMatrix.clone();
  109. invertPivotMatrix.invert();
  110. var translateMatrix = invertRotationMatrix.multiply(invertScalingMatrix);
  111. translateMatrix.multiplyToRef(invertPivotMatrix, invertScalingMatrix); // reuse matrix
  112. invertScalingMatrix.multiplyToRef(worldMatrix, translateMatrix);
  113. if (this.parent) {
  114. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  115. invertParentWorldMatrix.invert();
  116. translateMatrix.multiplyToRef(invertParentWorldMatrix, invertScalingMatrix); // reuse matrix
  117. translateMatrix = invertScalingMatrix;
  118. }
  119. this.position.x = translateMatrix.m[12];
  120. this.position.y = translateMatrix.m[13];
  121. this.position.z = translateMatrix.m[14];
  122. };
  123. BABYLON.Mesh.prototype.getTotalVertices = function () {
  124. return this._totalVertices;
  125. };
  126. BABYLON.Mesh.prototype.getVerticesData = function (kind) {
  127. return this._vertexBuffers[kind].getData();
  128. };
  129. BABYLON.Mesh.prototype.getVertexBuffer = function (kind) {
  130. return this._vertexBuffers[kind];
  131. };
  132. BABYLON.Mesh.prototype.isVerticesDataPresent = function (kind) {
  133. if (!this._vertexBuffers && this._delayInfo) {
  134. return this._delayInfo.indexOf(kind) !== -1;
  135. }
  136. return this._vertexBuffers[kind] !== undefined;
  137. };
  138. BABYLON.Mesh.prototype.getVerticesDataKinds = function () {
  139. var result = [];
  140. if (!this._vertexBuffers && this._delayInfo) {
  141. for (var kind in this._delayInfo) {
  142. result.push(kind);
  143. }
  144. } else {
  145. for (var kind in this._vertexBuffers) {
  146. result.push(kind);
  147. }
  148. }
  149. return result;
  150. };
  151. BABYLON.Mesh.prototype.getTotalIndices = function () {
  152. return this._indices.length;
  153. };
  154. BABYLON.Mesh.prototype.getIndices = function () {
  155. return this._indices;
  156. };
  157. BABYLON.Mesh.prototype.getVertexStrideSize = function () {
  158. return this._vertexStrideSize;
  159. };
  160. BABYLON.Mesh.prototype.setPivotMatrix = function (matrix) {
  161. this._pivotMatrix = matrix;
  162. this._cache.pivotMatrixUpdated = true;
  163. };
  164. BABYLON.Mesh.prototype.getPivotMatrix = function () {
  165. return this._pivotMatrix;
  166. };
  167. BABYLON.Mesh.prototype._isSynchronized = function () {
  168. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE)
  169. return false;
  170. if (this._cache.pivotMatrixUpdated) {
  171. return false;
  172. }
  173. if (this.infiniteDistance) {
  174. return false;
  175. }
  176. if (!this._cache.position.equals(this.position))
  177. return false;
  178. if (this.rotationQuaternion) {
  179. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  180. return false;
  181. } else {
  182. if (!this._cache.rotation.equals(this.rotation))
  183. return false;
  184. }
  185. if (!this._cache.scaling.equals(this.scaling))
  186. return false;
  187. return true;
  188. };
  189. BABYLON.Mesh.prototype.isReady = function () {
  190. return this._isReady;
  191. };
  192. BABYLON.Mesh.prototype.isAnimated = function () {
  193. return this._animationStarted;
  194. };
  195. BABYLON.Mesh.prototype.isDisposed = function () {
  196. return this._isDisposed;
  197. };
  198. // Methods
  199. BABYLON.Mesh.prototype._initCache = function () {
  200. this._cache.localMatrixUpdated = false;
  201. this._cache.position = BABYLON.Vector3.Zero();
  202. this._cache.scaling = BABYLON.Vector3.Zero();
  203. this._cache.rotation = BABYLON.Vector3.Zero();
  204. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  205. };
  206. BABYLON.Mesh.prototype.markAsDirty = function (property) {
  207. if (property === "rotation") {
  208. this.rotationQuaternion = null;
  209. }
  210. this._syncChildFlag();
  211. };
  212. BABYLON.Mesh.prototype.refreshBoundingInfo = function () {
  213. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  214. if (!data) {
  215. return;
  216. }
  217. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  218. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  219. for (var index = 0; index < this.subMeshes.length; index++) {
  220. this.subMeshes[index].refreshBoundingInfo();
  221. }
  222. this._updateBoundingInfo();
  223. };
  224. BABYLON.Mesh.prototype._updateBoundingInfo = function () {
  225. if (this._boundingInfo) {
  226. this._scaleFactor = Math.max(this.scaling.x, this.scaling.y);
  227. this._scaleFactor = Math.max(this._scaleFactor, this.scaling.z);
  228. if (this.parent && this.parent._scaleFactor)
  229. this._scaleFactor = this._scaleFactor * this.parent._scaleFactor;
  230. this._boundingInfo._update(this._worldMatrix, this._scaleFactor);
  231. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  232. var subMesh = this.subMeshes[subIndex];
  233. subMesh.updateBoundingInfo(this._worldMatrix, this._scaleFactor);
  234. }
  235. }
  236. };
  237. BABYLON.Mesh.prototype.computeWorldMatrix = function (force) {
  238. if (!force && (this._currentRenderId == this._scene.getRenderId() || this.isSynchronized(true))) {
  239. return this._worldMatrix;
  240. }
  241. this._syncChildFlag();
  242. this._cache.position.copyFrom(this.position);
  243. this._cache.scaling.copyFrom(this.scaling);
  244. this._cache.pivotMatrixUpdated = false;
  245. this._currentRenderId = this._scene.getRenderId();
  246. // Scaling
  247. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  248. // Rotation
  249. if (this.rotationQuaternion) {
  250. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  251. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  252. } else {
  253. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  254. this._cache.rotation.copyFrom(this.rotation);
  255. }
  256. // Translation
  257. if (this.infiniteDistance) {
  258. var camera = this._scene.activeCamera;
  259. BABYLON.Matrix.TranslationToRef(this.position.x + camera.position.x, this.position.y + camera.position.y, this.position.z + camera.position.z, this._localTranslation);
  260. } else {
  261. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  262. }
  263. // Composing transformations
  264. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  265. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  266. // Billboarding
  267. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE) {
  268. var localPosition = this.position.clone();
  269. var zero = this._scene.activeCamera.position.clone();
  270. if (this.parent && this.parent.position) {
  271. localPosition.addInPlace(this.parent.position);
  272. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  273. }
  274. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_ALL === BABYLON.Mesh.BILLBOARDMODE_ALL) {
  275. zero = this._scene.activeCamera.position;
  276. } else {
  277. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  278. zero.x = localPosition.x + BABYLON.Engine.epsilon;
  279. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  280. zero.y = localPosition.y + BABYLON.Engine.epsilon;
  281. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  282. zero.z = localPosition.z + BABYLON.Engine.epsilon;
  283. }
  284. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  285. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  286. this._localBillboard.invert();
  287. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  288. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  289. }
  290. // Local world
  291. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  292. // Parent
  293. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  294. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  295. } else {
  296. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._worldMatrix);
  297. }
  298. // Bounding info
  299. this._updateBoundingInfo();
  300. // Absolute position
  301. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  302. return this._worldMatrix;
  303. };
  304. BABYLON.Mesh.prototype._createGlobalSubMesh = function () {
  305. if (!this._totalVertices || !this._indices) {
  306. return null;
  307. }
  308. this.subMeshes = [];
  309. return new BABYLON.SubMesh(0, 0, this._totalVertices, 0, this._indices.length, this);
  310. };
  311. BABYLON.Mesh.prototype.subdivide = function (count) {
  312. if (count < 1) {
  313. return;
  314. }
  315. var subdivisionSize = this._indices.length / count;
  316. var offset = 0;
  317. this.subMeshes = [];
  318. for (var index = 0; index < count; index++) {
  319. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, this._indices.length - offset), this);
  320. offset += subdivisionSize;
  321. }
  322. };
  323. BABYLON.Mesh.prototype.setVerticesData = function (data, kind, updatable) {
  324. if (!this._vertexBuffers) {
  325. this._vertexBuffers = {};
  326. }
  327. if (this._vertexBuffers[kind]) {
  328. this._vertexBuffers[kind].dispose();
  329. }
  330. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this, data, kind, updatable);
  331. if (kind === BABYLON.VertexBuffer.PositionKind) {
  332. var stride = this._vertexBuffers[kind].getStrideSize();
  333. this._totalVertices = data.length / stride;
  334. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  335. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  336. this._createGlobalSubMesh();
  337. }
  338. };
  339. BABYLON.Mesh.prototype.updateVerticesData = function (kind, data) {
  340. if (this._vertexBuffers[kind]) {
  341. this._vertexBuffers[kind].update(data);
  342. }
  343. };
  344. BABYLON.Mesh.prototype.setIndices = function (indices) {
  345. if (this._indexBuffer) {
  346. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  347. }
  348. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  349. this._indices = indices;
  350. this._createGlobalSubMesh();
  351. };
  352. BABYLON.Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  353. var engine = this._scene.getEngine();
  354. // Wireframe
  355. var indexToBind = this._indexBuffer;
  356. var useTriangles = true;
  357. if (wireframe) {
  358. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  359. useTriangles = false;
  360. }
  361. // VBOs
  362. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  363. // Draw order
  364. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  365. };
  366. BABYLON.Mesh.prototype.registerBeforeRender = function (func) {
  367. this._onBeforeRenderCallbacks.push(func);
  368. };
  369. BABYLON.Mesh.prototype.unregisterBeforeRender = function (func) {
  370. var index = this._onBeforeRenderCallbacks.indexOf(func);
  371. if (index > -1) {
  372. this._onBeforeRenderCallbacks.splice(index, 1);
  373. }
  374. };
  375. BABYLON.Mesh.prototype.render = function (subMesh) {
  376. if (!this._vertexBuffers || !this._indexBuffer) {
  377. return;
  378. }
  379. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  380. this._onBeforeRenderCallbacks[callbackIndex]();
  381. }
  382. // World
  383. var world = this.getWorldMatrix();
  384. // Material
  385. var effectiveMaterial = subMesh.getMaterial();
  386. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  387. return;
  388. }
  389. effectiveMaterial._preBind();
  390. effectiveMaterial.bind(world, this);
  391. // Bind and draw
  392. var engine = this._scene.getEngine();
  393. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  394. // Unbind
  395. effectiveMaterial.unbind();
  396. };
  397. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  398. var results = [];
  399. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  400. var particleSystem = this._scene.particleSystems[index];
  401. if (particleSystem.emitter === this) {
  402. results.push(particleSystem);
  403. }
  404. }
  405. return results;
  406. };
  407. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  408. var results = [];
  409. var descendants = this.getDescendants();
  410. descendants.push(this);
  411. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  412. var particleSystem = this._scene.particleSystems[index];
  413. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  414. results.push(particleSystem);
  415. }
  416. }
  417. return results;
  418. };
  419. BABYLON.Mesh.prototype.getChildren = function () {
  420. var results = [];
  421. for (var index = 0; index < this._scene.meshes.length; index++) {
  422. var mesh = this._scene.meshes[index];
  423. if (mesh.parent == this) {
  424. results.push(mesh);
  425. }
  426. }
  427. return results;
  428. };
  429. BABYLON.Mesh.prototype.isInFrustum = function (frustumPlanes) {
  430. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  431. return false;
  432. }
  433. var result = this._boundingInfo.isInFrustum(frustumPlanes);
  434. if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  435. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  436. var that = this;
  437. this._scene._addPendingData(this);
  438. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  439. BABYLON.SceneLoader._ImportGeometry(JSON.parse(data), that);
  440. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  441. that._scene._removePendingData(that);
  442. }, function () { }, this._scene.database);
  443. }
  444. return result;
  445. };
  446. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  447. var materials = this._scene.materials;
  448. for (var index = 0; index < materials.length; index++) {
  449. if (materials[index].id == id) {
  450. this.material = materials[index];
  451. return;
  452. }
  453. }
  454. // Multi
  455. var multiMaterials = this._scene.multiMaterials;
  456. for (var index = 0; index < multiMaterials.length; index++) {
  457. if (multiMaterials[index].id == id) {
  458. this.material = multiMaterials[index];
  459. return;
  460. }
  461. }
  462. };
  463. BABYLON.Mesh.prototype.getAnimatables = function () {
  464. var results = [];
  465. if (this.material) {
  466. results.push(this.material);
  467. }
  468. return results;
  469. };
  470. // Geometry
  471. // Deprecated: use setPositionWithLocalVector instead
  472. BABYLON.Mesh.prototype.setLocalTranslation = function (vector3) {
  473. console.warn("deprecated: use setPositionWithLocalVector instead");
  474. this.computeWorldMatrix();
  475. var worldMatrix = this._worldMatrix.clone();
  476. worldMatrix.setTranslation(BABYLON.Vector3.Zero());
  477. this.position = BABYLON.Vector3.TransformCoordinates(vector3, worldMatrix);
  478. };
  479. // Deprecated: use getPositionExpressedInLocalSpace instead
  480. BABYLON.Mesh.prototype.getLocalTranslation = function () {
  481. console.warn("deprecated: use getPositionExpressedInLocalSpace instead");
  482. this.computeWorldMatrix();
  483. var invWorldMatrix = this._worldMatrix.clone();
  484. invWorldMatrix.setTranslation(BABYLON.Vector3.Zero());
  485. invWorldMatrix.invert();
  486. return BABYLON.Vector3.TransformCoordinates(this.position, invWorldMatrix);
  487. };
  488. BABYLON.Mesh.prototype.setPositionWithLocalVector = function (vector3) {
  489. this.computeWorldMatrix();
  490. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  491. };
  492. BABYLON.Mesh.prototype.getPositionExpressedInLocalSpace = function () {
  493. this.computeWorldMatrix();
  494. var invLocalWorldMatrix = this._localWorld.clone();
  495. invLocalWorldMatrix.invert();
  496. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  497. };
  498. BABYLON.Mesh.prototype.locallyTranslate = function (vector3) {
  499. this.computeWorldMatrix();
  500. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  501. };
  502. BABYLON.Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  503. // Position
  504. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  505. return;
  506. }
  507. this._resetPointsArrayCache();
  508. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  509. var temp = new BABYLON.MatrixType(data.length);
  510. for (var index = 0; index < data.length; index += 3) {
  511. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  512. }
  513. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].isUpdatable());
  514. // Normals
  515. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  516. return;
  517. }
  518. data = this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].getData();
  519. for (var index = 0; index < data.length; index += 3) {
  520. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  521. }
  522. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].isUpdatable());
  523. };
  524. BABYLON.Mesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  525. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  526. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  527. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  528. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  529. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  530. /// <returns>Mesh oriented towards targetMesh</returns>
  531. yawCor = yawCor || 0; // default to zero if undefined
  532. pitchCor = pitchCor || 0;
  533. rollCor = rollCor || 0;
  534. var dv = targetPoint.subtract(this.position);
  535. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  536. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  537. var pitch = Math.atan2(dv.y, len);
  538. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  539. };
  540. // Cache
  541. BABYLON.Mesh.prototype._resetPointsArrayCache = function () {
  542. this._positions = null;
  543. };
  544. BABYLON.Mesh.prototype._generatePointsArray = function () {
  545. if (this._positions)
  546. return;
  547. this._positions = [];
  548. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  549. for (var index = 0; index < data.length; index += 3) {
  550. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  551. }
  552. };
  553. // Collisions
  554. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  555. this._generatePointsArray();
  556. // Transformation
  557. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  558. subMesh._lastColliderTransformMatrix = transformMatrix;
  559. subMesh._lastColliderWorldVertices = [];
  560. var start = subMesh.verticesStart;
  561. var end = (subMesh.verticesStart + subMesh.verticesCount);
  562. for (var i = start; i < end; i++) {
  563. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  564. }
  565. }
  566. // Collide
  567. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  568. };
  569. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  570. for (var index = 0; index < this.subMeshes.length; index++) {
  571. var subMesh = this.subMeshes[index];
  572. // Bounding test
  573. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  574. continue;
  575. this._collideForSubMesh(subMesh, transformMatrix, collider);
  576. }
  577. };
  578. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  579. // Bounding box test
  580. if (!this._boundingInfo._checkCollision(collider))
  581. return;
  582. // Transformation matrix
  583. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  584. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  585. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  586. };
  587. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  588. if (!this._boundingInfo || !mesh._boundingInfo) {
  589. return false;
  590. }
  591. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  592. };
  593. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  594. if (!this._boundingInfo) {
  595. return false;
  596. }
  597. return this._boundingInfo.intersectsPoint(point);
  598. };
  599. // Picking
  600. BABYLON.Mesh.prototype.intersects = function (ray, fastCheck) {
  601. var pickingInfo = new BABYLON.PickingInfo();
  602. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  603. return pickingInfo;
  604. }
  605. this._generatePointsArray();
  606. var distance = Number.MAX_VALUE;
  607. for (var index = 0; index < this.subMeshes.length; index++) {
  608. var subMesh = this.subMeshes[index];
  609. // Bounding test
  610. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  611. continue;
  612. var currentDistance = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  613. if (currentDistance > 0) {
  614. if (fastCheck || currentDistance < distance) {
  615. distance = currentDistance;
  616. if (fastCheck) {
  617. break;
  618. }
  619. }
  620. }
  621. }
  622. if (distance >= 0 && distance < Number.MAX_VALUE) {
  623. // Get picked point
  624. var world = this.getWorldMatrix();
  625. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  626. var direction = ray.direction.clone();
  627. direction.normalize();
  628. direction = direction.scale(distance);
  629. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  630. var pickedPoint = worldOrigin.add(worldDirection);
  631. // Return result
  632. pickingInfo.hit = true;
  633. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  634. pickingInfo.pickedPoint = pickedPoint;
  635. pickingInfo.pickedMesh = this;
  636. return pickingInfo;
  637. }
  638. return pickingInfo;
  639. };
  640. // Clone
  641. BABYLON.Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  642. var result = new BABYLON.Mesh(name, this._scene);
  643. // Buffers
  644. result._vertexBuffers = this._vertexBuffers;
  645. for (var kind in result._vertexBuffers) {
  646. result._vertexBuffers[kind].references++;
  647. }
  648. result._indexBuffer = this._indexBuffer;
  649. this._indexBuffer.references++;
  650. // Deep copy
  651. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  652. // Bounding info
  653. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  654. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  655. // Material
  656. result.material = this.material;
  657. // Parent
  658. if (newParent) {
  659. result.parent = newParent;
  660. }
  661. if (!doNotCloneChildren) {
  662. // Children
  663. for (var index = 0; index < this._scene.meshes.length; index++) {
  664. var mesh = this._scene.meshes[index];
  665. if (mesh.parent == this) {
  666. mesh.clone(mesh.name, result);
  667. }
  668. }
  669. }
  670. // Particles
  671. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  672. var system = this._scene.particleSystems[index];
  673. if (system.emitter == this) {
  674. system.clone(system.name, result);
  675. }
  676. }
  677. result.computeWorldMatrix(true);
  678. return result;
  679. };
  680. // Dispose
  681. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  682. if (this._vertexBuffers) {
  683. for (var index = 0; index < this._vertexBuffers.length; index++) {
  684. this._vertexBuffers[index].dispose();
  685. }
  686. this._vertexBuffers = null;
  687. }
  688. if (this._indexBuffer) {
  689. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  690. this._indexBuffer = null;
  691. }
  692. // Remove from scene
  693. var index = this._scene.meshes.indexOf(this);
  694. this._scene.meshes.splice(index, 1);
  695. if (!doNotRecurse) {
  696. // Particles
  697. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  698. if (this._scene.particleSystems[index].emitter == this) {
  699. this._scene.particleSystems[index].dispose();
  700. index--;
  701. }
  702. }
  703. // Children
  704. var objects = this._scene.meshes.slice(0);
  705. for (var index = 0; index < objects.length; index++) {
  706. if (objects[index].parent == this) {
  707. objects[index].dispose();
  708. }
  709. }
  710. } else {
  711. for (var index = 0; index < this._scene.meshes.length; index++) {
  712. var obj = this._scene.meshes[index];
  713. if (obj.parent === this) {
  714. obj.parent = null;
  715. obj.computeWorldMatrix(true);
  716. }
  717. }
  718. }
  719. this._isDisposed = true;
  720. // Callback
  721. if (this.onDispose) {
  722. this.onDispose();
  723. }
  724. };
  725. // Physics
  726. BABYLON.Mesh.prototype.setPhysicsState = function (options) {
  727. if (!this._scene._physicsEngine) {
  728. return;
  729. }
  730. options.impostor = options.impostor || BABYLON.PhysicsEngine.NoImpostor;
  731. options.mass = options.mass || 0;
  732. options.friction = options.friction || 0.2;
  733. options.restitution = options.restitution || 0.9;
  734. this._physicImpostor = options.impostor;
  735. this._physicsMass = options.mass;
  736. this._physicsFriction = options.friction;
  737. this._physicRestitution = options.restitution;
  738. if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
  739. this._scene._physicsEngine._unregisterMesh(this);
  740. return;
  741. }
  742. this._scene._physicsEngine._registerMesh(this, options);
  743. };
  744. BABYLON.Mesh.prototype.getPhysicsImpostor = function () {
  745. if (!this._physicImpostor) {
  746. return BABYLON.PhysicsEngine.NoImpostor;
  747. }
  748. return this._physicImpostor;
  749. };
  750. BABYLON.Mesh.prototype.getPhysicsMass = function () {
  751. if (!this._physicsMass) {
  752. return 0;
  753. }
  754. return this._physicsMass;
  755. };
  756. BABYLON.Mesh.prototype.getPhysicsFriction = function () {
  757. if (!this._physicsFriction) {
  758. return 0;
  759. }
  760. return this._physicsFriction;
  761. };
  762. BABYLON.Mesh.prototype.getPhysicsRestitution = function () {
  763. if (!this._physicRestitution) {
  764. return 0;
  765. }
  766. return this._physicRestitution;
  767. };
  768. BABYLON.Mesh.prototype.applyImpulse = function (force, contactPoint) {
  769. if (!this._physicImpostor) {
  770. return;
  771. }
  772. this._scene._physicsEngine._applyImpulse(this, force, contactPoint);
  773. };
  774. BABYLON.Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
  775. if (!this._physicImpostor) {
  776. return;
  777. }
  778. this._scene._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
  779. };
  780. // Geometric tools
  781. BABYLON.Mesh.prototype.convertToFlatShadedMesh = function() {
  782. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  783. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  784. var kinds = this.getVerticesDataKinds();
  785. var vbs = [];
  786. var data = [];
  787. var newdata = [];
  788. var updatableNormals = false;
  789. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  790. var kind = kinds[kindIndex];
  791. if (kind === BABYLON.VertexBuffer.NormalKind) {
  792. updatableNormals = this.getVertexBuffer(kind).isUpdatable();
  793. kinds.splice(kindIndex, 1);
  794. kindIndex--;
  795. continue;
  796. }
  797. vbs[kind] = this.getVertexBuffer(kind);
  798. data[kind] = vbs[kind].getData();
  799. newdata[kind] = [];
  800. }
  801. // Save previous submeshes
  802. var previousSubmeshes = this.subMeshes.slice(0);
  803. var indices = this.getIndices();
  804. // Generating unique vertices per face
  805. for (var index = 0; index < indices.length; index++) {
  806. var vertexIndex = indices[index];
  807. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  808. var kind = kinds[kindIndex];
  809. var stride = vbs[kind].getStrideSize();
  810. for (var offset = 0; offset < stride; offset++) {
  811. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  812. }
  813. }
  814. }
  815. // Updating faces & normal
  816. var normals = [];
  817. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  818. for (var index = 0; index < indices.length; index += 3) {
  819. indices[index] = index;
  820. indices[index + 1] = index + 1;
  821. indices[index + 2] = index + 2;
  822. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  823. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  824. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  825. var p1p2 = p1.subtract(p2);
  826. var p3p2 = p3.subtract(p2);
  827. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  828. // Store same normals for every vertex
  829. for (var localIndex = 0; localIndex < 3; localIndex++) {
  830. normals.push(normal.x);
  831. normals.push(normal.y);
  832. normals.push(normal.z);
  833. }
  834. }
  835. this.setIndices(indices);
  836. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  837. // Updating vertex buffers
  838. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  839. var kind = kinds[kindIndex];
  840. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  841. }
  842. // Updating submeshes
  843. this.subMeshes = [];
  844. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  845. var previousOne = previousSubmeshes[submeshIndex];
  846. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  847. }
  848. };
  849. // Statics
  850. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  851. var box = new BABYLON.Mesh(name, scene);
  852. var normalsSource = [
  853. new BABYLON.Vector3(0, 0, 1),
  854. new BABYLON.Vector3(0, 0, -1),
  855. new BABYLON.Vector3(1, 0, 0),
  856. new BABYLON.Vector3(-1, 0, 0),
  857. new BABYLON.Vector3(0, 1, 0),
  858. new BABYLON.Vector3(0, -1, 0)
  859. ];
  860. var indices = [];
  861. var positions = [];
  862. var normals = [];
  863. var uvs = [];
  864. // Create each face in turn.
  865. for (var index = 0; index < normalsSource.length; index++) {
  866. var normal = normalsSource[index];
  867. // Get two vectors perpendicular to the face normal and to each other.
  868. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  869. var side2 = BABYLON.Vector3.Cross(normal, side1);
  870. // Six indices (two triangles) per face.
  871. var verticesLength = positions.length / 3;
  872. indices.push(verticesLength);
  873. indices.push(verticesLength + 1);
  874. indices.push(verticesLength + 2);
  875. indices.push(verticesLength);
  876. indices.push(verticesLength + 2);
  877. indices.push(verticesLength + 3);
  878. // Four vertices per face.
  879. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  880. positions.push(vertex.x, vertex.y, vertex.z);
  881. normals.push(normal.x, normal.y, normal.z);
  882. uvs.push(1.0, 1.0);
  883. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  884. positions.push(vertex.x, vertex.y, vertex.z);
  885. normals.push(normal.x, normal.y, normal.z);
  886. uvs.push(0.0, 1.0);
  887. vertex = normal.add(side1).add(side2).scale(size / 2);
  888. positions.push(vertex.x, vertex.y, vertex.z);
  889. normals.push(normal.x, normal.y, normal.z);
  890. uvs.push(0.0, 0.0);
  891. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  892. positions.push(vertex.x, vertex.y, vertex.z);
  893. normals.push(normal.x, normal.y, normal.z);
  894. uvs.push(1.0, 0.0);
  895. }
  896. box.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  897. box.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  898. box.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  899. box.setIndices(indices);
  900. return box;
  901. };
  902. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  903. var sphere = new BABYLON.Mesh(name, scene);
  904. var radius = diameter / 2;
  905. var totalZRotationSteps = 2 + segments;
  906. var totalYRotationSteps = 2 * totalZRotationSteps;
  907. var indices = [];
  908. var positions = [];
  909. var normals = [];
  910. var uvs = [];
  911. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  912. var normalizedZ = zRotationStep / totalZRotationSteps;
  913. var angleZ = (normalizedZ * Math.PI);
  914. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  915. var normalizedY = yRotationStep / totalYRotationSteps;
  916. var angleY = normalizedY * Math.PI * 2;
  917. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  918. var rotationY = BABYLON.Matrix.RotationY(angleY);
  919. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  920. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  921. var vertex = complete.scale(radius);
  922. var normal = BABYLON.Vector3.Normalize(vertex);
  923. positions.push(vertex.x, vertex.y, vertex.z);
  924. normals.push(normal.x, normal.y, normal.z);
  925. uvs.push(normalizedZ, normalizedY);
  926. }
  927. if (zRotationStep > 0) {
  928. var verticesCount = positions.length / 3;
  929. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  930. indices.push((firstIndex));
  931. indices.push((firstIndex + 1));
  932. indices.push(firstIndex + totalYRotationSteps + 1);
  933. indices.push((firstIndex + totalYRotationSteps + 1));
  934. indices.push((firstIndex + 1));
  935. indices.push((firstIndex + totalYRotationSteps + 2));
  936. }
  937. }
  938. }
  939. sphere.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  940. sphere.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  941. sphere.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  942. sphere.setIndices(indices);
  943. return sphere;
  944. };
  945. // Cylinder and cone (Code inspired by SharpDX.org)
  946. BABYLON.Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
  947. var radiusTop = diameterTop / 2;
  948. var radiusBottom = diameterBottom / 2;
  949. var indices = [];
  950. var positions = [];
  951. var normals = [];
  952. var uvs = [];
  953. var cylinder = new BABYLON.Mesh(name, scene);
  954. var getCircleVector = function (i) {
  955. var angle = (i * 2.0 * Math.PI / tessellation);
  956. var dx = Math.sin(angle);
  957. var dz = Math.cos(angle);
  958. return new BABYLON.Vector3(dx, 0, dz);
  959. };
  960. var createCylinderCap = function (isTop) {
  961. var radius = isTop ? radiusTop : radiusBottom;
  962. if (radius == 0) {
  963. return
  964. }
  965. // Create cap indices.
  966. for (var i = 0; i < tessellation - 2; i++) {
  967. var i1 = (i + 1) % tessellation;
  968. var i2 = (i + 2) % tessellation;
  969. if (!isTop) {
  970. var tmp = i1;
  971. var i1 = i2;
  972. i2 = tmp;
  973. }
  974. var vbase = positions.length / 3;
  975. indices.push(vbase);
  976. indices.push(vbase + i1);
  977. indices.push(vbase + i2);
  978. }
  979. // Which end of the cylinder is this?
  980. var normal = new BABYLON.Vector3(0, -1, 0);
  981. var textureScale = new BABYLON.Vector2(-0.5, -0.5);
  982. if (!isTop) {
  983. normal = normal.scale(-1);
  984. textureScale.x = -textureScale.x;
  985. }
  986. // Create cap vertices.
  987. for (var i = 0; i < tessellation; i++) {
  988. var circleVector = getCircleVector(i);
  989. var position = circleVector.scale(radius).add(normal.scale(height));
  990. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  991. positions.push(position.x, position.y, position.z);
  992. normals.push(normal.x, normal.y, normal.z);
  993. uvs.push(textureCoordinate.x, textureCoordinate.y);
  994. }
  995. };
  996. height /= 2;
  997. var topOffset = new BABYLON.Vector3(0, 1, 0).scale(height);
  998. var stride = tessellation + 1;
  999. // Create a ring of triangles around the outside of the cylinder.
  1000. for (var i = 0; i <= tessellation; i++) {
  1001. var normal = getCircleVector(i);
  1002. var sideOffsetBottom = normal.scale(radiusBottom);
  1003. var sideOffsetTop = normal.scale(radiusTop);
  1004. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  1005. var position = sideOffsetBottom.add(topOffset);
  1006. positions.push(position.x, position.y, position.z);
  1007. normals.push(normal.x, normal.y, normal.z);
  1008. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1009. position = sideOffsetTop.subtract(topOffset);
  1010. textureCoordinate.y += 1;
  1011. positions.push(position.x, position.y, position.z);
  1012. normals.push(normal.x, normal.y, normal.z);
  1013. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1014. indices.push(i * 2);
  1015. indices.push((i * 2 + 2) % (stride * 2));
  1016. indices.push(i * 2 + 1);
  1017. indices.push(i * 2 + 1);
  1018. indices.push((i * 2 + 2) % (stride * 2));
  1019. indices.push((i * 2 + 3) % (stride * 2));
  1020. }
  1021. // Create flat triangle fan caps to seal the top and bottom.
  1022. createCylinderCap(true);
  1023. createCylinderCap(false);
  1024. cylinder.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1025. cylinder.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1026. cylinder.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1027. cylinder.setIndices(indices);
  1028. return cylinder;
  1029. };
  1030. // Torus (Code from SharpDX.org)
  1031. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  1032. var torus = new BABYLON.Mesh(name, scene);
  1033. var indices = [];
  1034. var positions = [];
  1035. var normals = [];
  1036. var uvs = [];
  1037. var stride = tessellation + 1;
  1038. for (var i = 0; i <= tessellation; i++) {
  1039. var u = i / tessellation;
  1040. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  1041. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  1042. for (var j = 0; j <= tessellation; j++) {
  1043. var v = 1 - j / tessellation;
  1044. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  1045. var dx = Math.cos(innerAngle);
  1046. var dy = Math.sin(innerAngle);
  1047. // Create a vertex.
  1048. var normal = new BABYLON.Vector3(dx, dy, 0);
  1049. var position = normal.scale(thickness / 2);
  1050. var textureCoordinate = new BABYLON.Vector2(u, v);
  1051. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  1052. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  1053. positions.push(position.x, position.y, position.z);
  1054. normals.push(normal.x, normal.y, normal.z);
  1055. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1056. // And create indices for two triangles.
  1057. var nextI = (i + 1) % stride;
  1058. var nextJ = (j + 1) % stride;
  1059. indices.push(i * stride + j);
  1060. indices.push(i * stride + nextJ);
  1061. indices.push(nextI * stride + j);
  1062. indices.push(i * stride + nextJ);
  1063. indices.push(nextI * stride + nextJ);
  1064. indices.push(nextI * stride + j);
  1065. }
  1066. }
  1067. torus.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1068. torus.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1069. torus.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1070. torus.setIndices(indices);
  1071. return torus;
  1072. };
  1073. // Plane
  1074. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  1075. var plane = new BABYLON.Mesh(name, scene);
  1076. var indices = [];
  1077. var positions = [];
  1078. var normals = [];
  1079. var uvs = [];
  1080. // Vertices
  1081. var halfSize = size / 2.0;
  1082. positions.push(-halfSize, -halfSize, 0);
  1083. normals.push(0, 0, -1.0);
  1084. uvs.push(0.0, 0.0);
  1085. positions.push(halfSize, -halfSize, 0);
  1086. normals.push(0, 0, -1.0);
  1087. uvs.push(1.0, 0.0);
  1088. positions.push(halfSize, halfSize, 0);
  1089. normals.push(0, 0, -1.0);
  1090. uvs.push(1.0, 1.0);
  1091. positions.push(-halfSize, halfSize, 0);
  1092. normals.push(0, 0, -1.0);
  1093. uvs.push(0.0, 1.0);
  1094. // Indices
  1095. indices.push(0);
  1096. indices.push(1);
  1097. indices.push(2);
  1098. indices.push(0);
  1099. indices.push(2);
  1100. indices.push(3);
  1101. plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1102. plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1103. plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1104. plane.setIndices(indices);
  1105. return plane;
  1106. };
  1107. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  1108. var ground = new BABYLON.Mesh(name, scene);
  1109. var indices = [];
  1110. var positions = [];
  1111. var normals = [];
  1112. var uvs = [];
  1113. var row, col;
  1114. for (row = 0; row <= subdivisions; row++) {
  1115. for (col = 0; col <= subdivisions; col++) {
  1116. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1117. var normal = new BABYLON.Vector3(0, 1.0, 0);
  1118. positions.push(position.x, position.y, position.z);
  1119. normals.push(normal.x, normal.y, normal.z);
  1120. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1121. }
  1122. }
  1123. for (row = 0; row < subdivisions; row++) {
  1124. for (col = 0; col < subdivisions; col++) {
  1125. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1126. indices.push(col + 1 + row * (subdivisions + 1));
  1127. indices.push(col + row * (subdivisions + 1));
  1128. indices.push(col + (row + 1) * (subdivisions + 1));
  1129. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1130. indices.push(col + row * (subdivisions + 1));
  1131. }
  1132. }
  1133. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1134. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1135. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1136. ground.setIndices(indices);
  1137. return ground;
  1138. };
  1139. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  1140. var ground = new BABYLON.Mesh(name, scene);
  1141. var onload = function (img) {
  1142. var indices = [];
  1143. var positions = [];
  1144. var normals = [];
  1145. var uvs = [];
  1146. var row, col;
  1147. // Getting height map data
  1148. var canvas = document.createElement("canvas");
  1149. var context = canvas.getContext("2d");
  1150. var heightMapWidth = img.width;
  1151. var heightMapHeight = img.height;
  1152. canvas.width = heightMapWidth;
  1153. canvas.height = heightMapHeight;
  1154. context.drawImage(img, 0, 0);
  1155. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1156. // Vertices
  1157. for (row = 0; row <= subdivisions; row++) {
  1158. for (col = 0; col <= subdivisions; col++) {
  1159. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1160. // Compute height
  1161. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  1162. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  1163. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  1164. var r = buffer[pos] / 255.0;
  1165. var g = buffer[pos + 1] / 255.0;
  1166. var b = buffer[pos + 2] / 255.0;
  1167. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1168. position.y = minHeight + (maxHeight - minHeight) * gradient;
  1169. // Add vertex
  1170. positions.push(position.x, position.y, position.z);
  1171. normals.push(0, 0, 0);
  1172. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1173. }
  1174. }
  1175. // Indices
  1176. for (row = 0; row < subdivisions; row++) {
  1177. for (col = 0; col < subdivisions; col++) {
  1178. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1179. indices.push(col + 1 + row * (subdivisions + 1));
  1180. indices.push(col + row * (subdivisions + 1));
  1181. indices.push(col + (row + 1) * (subdivisions + 1));
  1182. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1183. indices.push(col + row * (subdivisions + 1));
  1184. }
  1185. }
  1186. // Normals
  1187. BABYLON.Mesh.ComputeNormal(positions, normals, indices);
  1188. // Transfer
  1189. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1190. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1191. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1192. ground.setIndices(indices);
  1193. ground._isReady = true;
  1194. };
  1195. BABYLON.Tools.LoadImage(url, onload, scene.database);
  1196. ground._isReady = false;
  1197. return ground;
  1198. };
  1199. // Tools
  1200. BABYLON.Mesh.ComputeNormal = function (positions, normals, indices) {
  1201. var positionVectors = [];
  1202. var facesOfVertices = [];
  1203. var index;
  1204. for (index = 0; index < positions.length; index += 3) {
  1205. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  1206. positionVectors.push(vector3);
  1207. facesOfVertices.push([]);
  1208. }
  1209. // Compute normals
  1210. var facesNormals = [];
  1211. for (index = 0; index < indices.length / 3; index++) {
  1212. var i1 = indices[index * 3];
  1213. var i2 = indices[index * 3 + 1];
  1214. var i3 = indices[index * 3 + 2];
  1215. var p1 = positionVectors[i1];
  1216. var p2 = positionVectors[i2];
  1217. var p3 = positionVectors[i3];
  1218. var p1p2 = p1.subtract(p2);
  1219. var p3p2 = p3.subtract(p2);
  1220. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  1221. facesOfVertices[i1].push(index);
  1222. facesOfVertices[i2].push(index);
  1223. facesOfVertices[i3].push(index);
  1224. }
  1225. for (index = 0; index < positionVectors.length; index++) {
  1226. var faces = facesOfVertices[index];
  1227. var normal = BABYLON.Vector3.Zero();
  1228. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  1229. normal.addInPlace(facesNormals[faces[faceIndex]]);
  1230. }
  1231. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  1232. normals[index * 3] = normal.x;
  1233. normals[index * 3 + 1] = normal.y;
  1234. normals[index * 3 + 2] = normal.z;
  1235. }
  1236. };
  1237. })();