babylon.mesh.js 50 KB

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