babylon.mesh.js 54 KB

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