babylon.mesh.js 47 KB

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