babylon.mesh.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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. // Deprecated: use setPositionWithLocalVector instead
  408. BABYLON.Mesh.prototype.setLocalTranslation = function (vector3) {
  409. console.warn("deprecated: use setPositionWithLocalVector instead");
  410. this.computeWorldMatrix();
  411. var worldMatrix = this._worldMatrix.clone();
  412. worldMatrix.setTranslation(BABYLON.Vector3.Zero());
  413. this.position = BABYLON.Vector3.TransformCoordinates(vector3, worldMatrix);
  414. };
  415. // Deprecated: use getPositionExpressedInLocalSpace instead
  416. BABYLON.Mesh.prototype.getLocalTranslation = function () {
  417. console.warn("deprecated: use getPositionExpressedInLocalSpace instead");
  418. this.computeWorldMatrix();
  419. var invWorldMatrix = this._worldMatrix.clone();
  420. invWorldMatrix.setTranslation(BABYLON.Vector3.Zero());
  421. invWorldMatrix.invert();
  422. return BABYLON.Vector3.TransformCoordinates(this.position, invWorldMatrix);
  423. };
  424. BABYLON.Mesh.prototype.setPositionWithLocalVector = function (vector3) {
  425. this.computeWorldMatrix();
  426. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  427. };
  428. BABYLON.Mesh.prototype.getPositionExpressedInLocalSpace = function () {
  429. this.computeWorldMatrix();
  430. var invLocalWorldMatrix = this._localWorld.clone();
  431. invLocalWorldMatrix.invert();
  432. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  433. };
  434. BABYLON.Mesh.prototype.locallyTranslate = function (vector3) {
  435. this.computeWorldMatrix();
  436. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  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. BABYLON.Mesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  461. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  462. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  463. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  464. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  465. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  466. /// <returns>Mesh oriented towards targetMesh</returns>
  467. yawCor = yawCor || 0; // default to zero if undefined
  468. pitchCor = pitchCor || 0;
  469. rollCor = rollCor || 0;
  470. var dv = targetPoint.subtract(this.position);
  471. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  472. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  473. var pitch = Math.atan2(dv.y, len);
  474. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  475. };
  476. // Cache
  477. BABYLON.Mesh.prototype._resetPointsArrayCache = function () {
  478. this._positions = null;
  479. };
  480. BABYLON.Mesh.prototype._generatePointsArray = function () {
  481. if (this._positions)
  482. return;
  483. this._positions = [];
  484. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  485. for (var index = 0; index < data.length; index += 3) {
  486. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  487. }
  488. };
  489. // Collisions
  490. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  491. this._generatePointsArray();
  492. // Transformation
  493. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  494. subMesh._lastColliderTransformMatrix = transformMatrix;
  495. subMesh._lastColliderWorldVertices = [];
  496. var start = subMesh.verticesStart;
  497. var end = (subMesh.verticesStart + subMesh.verticesCount);
  498. for (var i = start; i < end; i++) {
  499. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  500. }
  501. }
  502. // Collide
  503. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  504. };
  505. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  506. for (var index = 0; index < this.subMeshes.length; index++) {
  507. var subMesh = this.subMeshes[index];
  508. // Bounding test
  509. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  510. continue;
  511. this._collideForSubMesh(subMesh, transformMatrix, collider);
  512. }
  513. };
  514. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  515. // Bounding box test
  516. if (!this._boundingInfo._checkCollision(collider))
  517. return;
  518. // Transformation matrix
  519. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  520. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  521. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  522. };
  523. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  524. if (!this._boundingInfo || !mesh._boundingInfo) {
  525. return false;
  526. }
  527. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  528. };
  529. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  530. if (!this._boundingInfo) {
  531. return false;
  532. }
  533. return this._boundingInfo.intersectsPoint(point);
  534. };
  535. // Picking
  536. BABYLON.Mesh.prototype.intersects = function (ray, fastCheck) {
  537. var pickingInfo = new BABYLON.PickingInfo();
  538. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  539. return pickingInfo;
  540. }
  541. this._generatePointsArray();
  542. var distance = Number.MAX_VALUE;
  543. for (var index = 0; index < this.subMeshes.length; index++) {
  544. var subMesh = this.subMeshes[index];
  545. // Bounding test
  546. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  547. continue;
  548. var currentDistance = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  549. if (currentDistance > 0) {
  550. if (fastCheck || currentDistance < distance) {
  551. distance = currentDistance;
  552. if (fastCheck) {
  553. break;
  554. }
  555. }
  556. }
  557. }
  558. if (distance >= 0 && distance < Number.MAX_VALUE) {
  559. // Get picked point
  560. var world = this.getWorldMatrix();
  561. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  562. var direction = ray.direction.clone();
  563. direction.normalize();
  564. direction = direction.scale(distance);
  565. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  566. var pickedPoint = worldOrigin.add(worldDirection);
  567. // Return result
  568. pickingInfo.hit = true;
  569. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  570. pickingInfo.pickedPoint = pickedPoint;
  571. pickingInfo.pickedMesh = this;
  572. return pickingInfo;
  573. }
  574. return pickingInfo;
  575. };
  576. // Clone
  577. BABYLON.Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  578. var result = new BABYLON.Mesh(name, this._scene);
  579. // Buffers
  580. result._vertexBuffers = this._vertexBuffers;
  581. for (var kind in result._vertexBuffers) {
  582. result._vertexBuffers[kind].references++;
  583. }
  584. result._indexBuffer = this._indexBuffer;
  585. this._indexBuffer.references++;
  586. // Deep copy
  587. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  588. // Bounding info
  589. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  590. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  591. // Material
  592. result.material = this.material;
  593. // Parent
  594. if (newParent) {
  595. result.parent = newParent;
  596. }
  597. if (!doNotCloneChildren) {
  598. // Children
  599. for (var index = 0; index < this._scene.meshes.length; index++) {
  600. var mesh = this._scene.meshes[index];
  601. if (mesh.parent == this) {
  602. mesh.clone(mesh.name, result);
  603. }
  604. }
  605. }
  606. // Particles
  607. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  608. var system = this._scene.particleSystems[index];
  609. if (system.emitter == this) {
  610. system.clone(system.name, result);
  611. }
  612. }
  613. result.computeWorldMatrix(true);
  614. return result;
  615. };
  616. // Dispose
  617. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  618. if (this._vertexBuffers) {
  619. for (var index = 0; index < this._vertexBuffers.length; index++) {
  620. this._vertexBuffers[index].dispose();
  621. }
  622. this._vertexBuffers = null;
  623. }
  624. if (this._indexBuffer) {
  625. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  626. this._indexBuffer = null;
  627. }
  628. // Remove from scene
  629. var index = this._scene.meshes.indexOf(this);
  630. this._scene.meshes.splice(index, 1);
  631. if (!doNotRecurse) {
  632. // Particles
  633. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  634. if (this._scene.particleSystems[index].emitter == this) {
  635. this._scene.particleSystems[index].dispose();
  636. index--;
  637. }
  638. }
  639. // Children
  640. var objects = this._scene.meshes.slice(0);
  641. for (var index = 0; index < objects.length; index++) {
  642. if (objects[index].parent == this) {
  643. objects[index].dispose();
  644. }
  645. }
  646. } else {
  647. for (var index = 0; index < this._scene.meshes.length; index++) {
  648. var obj = this._scene.meshes[index];
  649. if (obj.parent === this) {
  650. obj.parent = null;
  651. obj.computeWorldMatrix(true);
  652. }
  653. }
  654. }
  655. this._isDisposed = true;
  656. // Callback
  657. if (this.onDispose) {
  658. this.onDispose();
  659. }
  660. };
  661. // Physics
  662. BABYLON.Mesh.prototype.setPhysicsState = function (options) {
  663. if (!this._scene._physicsEngine) {
  664. return;
  665. }
  666. options.impostor = options.impostor || BABYLON.PhysicsEngine.NoImpostor;
  667. options.mass = options.mass || 0;
  668. options.friction = options.friction || 0.2;
  669. options.restitution = options.restitution || 0.9;
  670. this._physicImpostor = options.impostor;
  671. this._physicsMass = options.mass;
  672. this._physicsFriction = options.friction;
  673. this._physicRestitution = options.restitution;
  674. if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
  675. this._scene._physicsEngine._unregisterMesh(this);
  676. return;
  677. }
  678. this._scene._physicsEngine._registerMesh(this, options);
  679. };
  680. BABYLON.Mesh.prototype.getPhysicsImpostor = function () {
  681. if (!this._physicImpostor) {
  682. return BABYLON.PhysicsEngine.NoImpostor;
  683. }
  684. return this._physicImpostor;
  685. };
  686. BABYLON.Mesh.prototype.getPhysicsMass = function () {
  687. if (!this._physicsMass) {
  688. return 0;
  689. }
  690. return this._physicsMass;
  691. };
  692. BABYLON.Mesh.prototype.getPhysicsFriction = function () {
  693. if (!this._physicsFriction) {
  694. return 0;
  695. }
  696. return this._physicsFriction;
  697. };
  698. BABYLON.Mesh.prototype.getPhysicsRestitution = function () {
  699. if (!this._physicRestitution) {
  700. return 0;
  701. }
  702. return this._physicRestitution;
  703. };
  704. BABYLON.Mesh.prototype.applyImpulse = function (force, contactPoint) {
  705. if (!this._physicImpostor) {
  706. return;
  707. }
  708. this._scene._physicsEngine._applyImpulse(this, force, contactPoint);
  709. };
  710. BABYLON.Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
  711. if (!this._physicImpostor) {
  712. return;
  713. }
  714. this._scene._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
  715. };
  716. // Statics
  717. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  718. var box = new BABYLON.Mesh(name, scene);
  719. var normalsSource = [
  720. new BABYLON.Vector3(0, 0, 1),
  721. new BABYLON.Vector3(0, 0, -1),
  722. new BABYLON.Vector3(1, 0, 0),
  723. new BABYLON.Vector3(-1, 0, 0),
  724. new BABYLON.Vector3(0, 1, 0),
  725. new BABYLON.Vector3(0, -1, 0)
  726. ];
  727. var indices = [];
  728. var positions = [];
  729. var normals = [];
  730. var uvs = [];
  731. // Create each face in turn.
  732. for (var index = 0; index < normalsSource.length; index++) {
  733. var normal = normalsSource[index];
  734. // Get two vectors perpendicular to the face normal and to each other.
  735. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  736. var side2 = BABYLON.Vector3.Cross(normal, side1);
  737. // Six indices (two triangles) per face.
  738. var verticesLength = positions.length / 3;
  739. indices.push(verticesLength);
  740. indices.push(verticesLength + 1);
  741. indices.push(verticesLength + 2);
  742. indices.push(verticesLength);
  743. indices.push(verticesLength + 2);
  744. indices.push(verticesLength + 3);
  745. // Four vertices per face.
  746. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  747. positions.push(vertex.x, vertex.y, vertex.z);
  748. normals.push(normal.x, normal.y, normal.z);
  749. uvs.push(1.0, 1.0);
  750. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  751. positions.push(vertex.x, vertex.y, vertex.z);
  752. normals.push(normal.x, normal.y, normal.z);
  753. uvs.push(0.0, 1.0);
  754. vertex = normal.add(side1).add(side2).scale(size / 2);
  755. positions.push(vertex.x, vertex.y, vertex.z);
  756. normals.push(normal.x, normal.y, normal.z);
  757. uvs.push(0.0, 0.0);
  758. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  759. positions.push(vertex.x, vertex.y, vertex.z);
  760. normals.push(normal.x, normal.y, normal.z);
  761. uvs.push(1.0, 0.0);
  762. }
  763. box.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  764. box.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  765. box.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  766. box.setIndices(indices);
  767. return box;
  768. };
  769. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  770. var sphere = new BABYLON.Mesh(name, scene);
  771. var radius = diameter / 2;
  772. var totalZRotationSteps = 2 + segments;
  773. var totalYRotationSteps = 2 * totalZRotationSteps;
  774. var indices = [];
  775. var positions = [];
  776. var normals = [];
  777. var uvs = [];
  778. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  779. var normalizedZ = zRotationStep / totalZRotationSteps;
  780. var angleZ = (normalizedZ * Math.PI);
  781. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  782. var normalizedY = yRotationStep / totalYRotationSteps;
  783. var angleY = normalizedY * Math.PI * 2;
  784. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  785. var rotationY = BABYLON.Matrix.RotationY(angleY);
  786. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  787. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  788. var vertex = complete.scale(radius);
  789. var normal = BABYLON.Vector3.Normalize(vertex);
  790. positions.push(vertex.x, vertex.y, vertex.z);
  791. normals.push(normal.x, normal.y, normal.z);
  792. uvs.push(normalizedZ, normalizedY);
  793. }
  794. if (zRotationStep > 0) {
  795. var verticesCount = positions.length / 3;
  796. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  797. indices.push((firstIndex));
  798. indices.push((firstIndex + 1));
  799. indices.push(firstIndex + totalYRotationSteps + 1);
  800. indices.push((firstIndex + totalYRotationSteps + 1));
  801. indices.push((firstIndex + 1));
  802. indices.push((firstIndex + totalYRotationSteps + 2));
  803. }
  804. }
  805. }
  806. sphere.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  807. sphere.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  808. sphere.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  809. sphere.setIndices(indices);
  810. return sphere;
  811. };
  812. // Cylinder and cone (Code inspired by SharpDX.org)
  813. BABYLON.Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
  814. var radiusTop = diameterTop / 2;
  815. var radiusBottom = diameterBottom / 2;
  816. var indices = [];
  817. var positions = [];
  818. var normals = [];
  819. var uvs = [];
  820. var cylinder = new BABYLON.Mesh(name, scene);
  821. var getCircleVector = function (i) {
  822. var angle = (i * 2.0 * Math.PI / tessellation);
  823. var dx = Math.sin(angle);
  824. var dz = Math.cos(angle);
  825. return new BABYLON.Vector3(dx, 0, dz);
  826. };
  827. var createCylinderCap = function (isTop) {
  828. var radius = isTop ? radiusTop : radiusBottom;
  829. if (radius == 0) {
  830. return
  831. }
  832. // Create cap indices.
  833. for (var i = 0; i < tessellation - 2; i++) {
  834. var i1 = (i + 1) % tessellation;
  835. var i2 = (i + 2) % tessellation;
  836. if (!isTop) {
  837. var tmp = i1;
  838. var i1 = i2;
  839. i2 = tmp;
  840. }
  841. var vbase = positions.length / 3;
  842. indices.push(vbase);
  843. indices.push(vbase + i1);
  844. indices.push(vbase + i2);
  845. }
  846. // Which end of the cylinder is this?
  847. var normal = new BABYLON.Vector3(0, -1, 0);
  848. var textureScale = new BABYLON.Vector2(-0.5, -0.5);
  849. if (!isTop) {
  850. normal = normal.scale(-1);
  851. textureScale.x = -textureScale.x;
  852. }
  853. // Create cap vertices.
  854. for (var i = 0; i < tessellation; i++) {
  855. var circleVector = getCircleVector(i);
  856. var position = circleVector.scale(radius).add(normal.scale(height));
  857. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  858. positions.push(position.x, position.y, position.z);
  859. normals.push(normal.x, normal.y, normal.z);
  860. uvs.push(textureCoordinate.x, textureCoordinate.y);
  861. }
  862. };
  863. height /= 2;
  864. var topOffset = new BABYLON.Vector3(0, 1, 0).scale(height);
  865. var stride = tessellation + 1;
  866. // Create a ring of triangles around the outside of the cylinder.
  867. for (var i = 0; i <= tessellation; i++) {
  868. var normal = getCircleVector(i);
  869. var sideOffsetBottom = normal.scale(radiusBottom);
  870. var sideOffsetTop = normal.scale(radiusTop);
  871. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  872. var position = sideOffsetBottom.add(topOffset);
  873. positions.push(position.x, position.y, position.z);
  874. normals.push(normal.x, normal.y, normal.z);
  875. uvs.push(textureCoordinate.x, textureCoordinate.y);
  876. position = sideOffsetTop.subtract(topOffset);
  877. textureCoordinate.y += 1;
  878. positions.push(position.x, position.y, position.z);
  879. normals.push(normal.x, normal.y, normal.z);
  880. uvs.push(textureCoordinate.x, textureCoordinate.y);
  881. indices.push(i * 2);
  882. indices.push((i * 2 + 2) % (stride * 2));
  883. indices.push(i * 2 + 1);
  884. indices.push(i * 2 + 1);
  885. indices.push((i * 2 + 2) % (stride * 2));
  886. indices.push((i * 2 + 3) % (stride * 2));
  887. }
  888. // Create flat triangle fan caps to seal the top and bottom.
  889. createCylinderCap(true);
  890. createCylinderCap(false);
  891. cylinder.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  892. cylinder.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  893. cylinder.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  894. cylinder.setIndices(indices);
  895. return cylinder;
  896. };
  897. // Torus (Code from SharpDX.org)
  898. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  899. var torus = new BABYLON.Mesh(name, scene);
  900. var indices = [];
  901. var positions = [];
  902. var normals = [];
  903. var uvs = [];
  904. var stride = tessellation + 1;
  905. for (var i = 0; i <= tessellation; i++) {
  906. var u = i / tessellation;
  907. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  908. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  909. for (var j = 0; j <= tessellation; j++) {
  910. var v = 1 - j / tessellation;
  911. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  912. var dx = Math.cos(innerAngle);
  913. var dy = Math.sin(innerAngle);
  914. // Create a vertex.
  915. var normal = new BABYLON.Vector3(dx, dy, 0);
  916. var position = normal.scale(thickness / 2);
  917. var textureCoordinate = new BABYLON.Vector2(u, v);
  918. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  919. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  920. positions.push(position.x, position.y, position.z);
  921. normals.push(normal.x, normal.y, normal.z);
  922. uvs.push(textureCoordinate.x, textureCoordinate.y);
  923. // And create indices for two triangles.
  924. var nextI = (i + 1) % stride;
  925. var nextJ = (j + 1) % stride;
  926. indices.push(i * stride + j);
  927. indices.push(i * stride + nextJ);
  928. indices.push(nextI * stride + j);
  929. indices.push(i * stride + nextJ);
  930. indices.push(nextI * stride + nextJ);
  931. indices.push(nextI * stride + j);
  932. }
  933. }
  934. torus.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  935. torus.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  936. torus.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  937. torus.setIndices(indices);
  938. return torus;
  939. };
  940. // Plane
  941. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  942. var plane = new BABYLON.Mesh(name, scene);
  943. var indices = [];
  944. var positions = [];
  945. var normals = [];
  946. var uvs = [];
  947. // Vertices
  948. var halfSize = size / 2.0;
  949. positions.push(-halfSize, -halfSize, 0);
  950. normals.push(0, 0, -1.0);
  951. uvs.push(0.0, 0.0);
  952. positions.push(halfSize, -halfSize, 0);
  953. normals.push(0, 0, -1.0);
  954. uvs.push(1.0, 0.0);
  955. positions.push(halfSize, halfSize, 0);
  956. normals.push(0, 0, -1.0);
  957. uvs.push(1.0, 1.0);
  958. positions.push(-halfSize, halfSize, 0);
  959. normals.push(0, 0, -1.0);
  960. uvs.push(0.0, 1.0);
  961. // Indices
  962. indices.push(0);
  963. indices.push(1);
  964. indices.push(2);
  965. indices.push(0);
  966. indices.push(2);
  967. indices.push(3);
  968. plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  969. plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  970. plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  971. plane.setIndices(indices);
  972. return plane;
  973. };
  974. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  975. var ground = new BABYLON.Mesh(name, scene);
  976. var indices = [];
  977. var positions = [];
  978. var normals = [];
  979. var uvs = [];
  980. var row, col;
  981. for (row = 0; row <= subdivisions; row++) {
  982. for (col = 0; col <= subdivisions; col++) {
  983. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  984. var normal = new BABYLON.Vector3(0, 1.0, 0);
  985. positions.push(position.x, position.y, position.z);
  986. normals.push(normal.x, normal.y, normal.z);
  987. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  988. }
  989. }
  990. for (row = 0; row < subdivisions; row++) {
  991. for (col = 0; col < subdivisions; col++) {
  992. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  993. indices.push(col + 1 + row * (subdivisions + 1));
  994. indices.push(col + row * (subdivisions + 1));
  995. indices.push(col + (row + 1) * (subdivisions + 1));
  996. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  997. indices.push(col + row * (subdivisions + 1));
  998. }
  999. }
  1000. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1001. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1002. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1003. ground.setIndices(indices);
  1004. return ground;
  1005. };
  1006. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  1007. var ground = new BABYLON.Mesh(name, scene);
  1008. var onload = function (img) {
  1009. var indices = [];
  1010. var positions = [];
  1011. var normals = [];
  1012. var uvs = [];
  1013. var row, col;
  1014. // Getting height map data
  1015. var canvas = document.createElement("canvas");
  1016. var context = canvas.getContext("2d");
  1017. var heightMapWidth = img.width;
  1018. var heightMapHeight = img.height;
  1019. canvas.width = heightMapWidth;
  1020. canvas.height = heightMapHeight;
  1021. context.drawImage(img, 0, 0);
  1022. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1023. // Vertices
  1024. for (row = 0; row <= subdivisions; row++) {
  1025. for (col = 0; col <= subdivisions; col++) {
  1026. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1027. // Compute height
  1028. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  1029. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  1030. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  1031. var r = buffer[pos] / 255.0;
  1032. var g = buffer[pos + 1] / 255.0;
  1033. var b = buffer[pos + 2] / 255.0;
  1034. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1035. position.y = minHeight + (maxHeight - minHeight) * gradient;
  1036. // Add vertex
  1037. positions.push(position.x, position.y, position.z);
  1038. normals.push(0, 0, 0);
  1039. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1040. }
  1041. }
  1042. // Indices
  1043. for (row = 0; row < subdivisions; row++) {
  1044. for (col = 0; col < subdivisions; col++) {
  1045. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1046. indices.push(col + 1 + row * (subdivisions + 1));
  1047. indices.push(col + row * (subdivisions + 1));
  1048. indices.push(col + (row + 1) * (subdivisions + 1));
  1049. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1050. indices.push(col + row * (subdivisions + 1));
  1051. }
  1052. }
  1053. // Normals
  1054. BABYLON.Mesh.ComputeNormal(positions, normals, indices);
  1055. // Transfer
  1056. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1057. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1058. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1059. ground.setIndices(indices);
  1060. ground._isReady = true;
  1061. };
  1062. BABYLON.Tools.LoadImage(url, onload, scene.database);
  1063. ground._isReady = false;
  1064. return ground;
  1065. };
  1066. // Tools
  1067. BABYLON.Mesh.ComputeNormal = function (positions, normals, indices) {
  1068. var positionVectors = [];
  1069. var facesOfVertices = [];
  1070. var index;
  1071. for (index = 0; index < positions.length; index += 3) {
  1072. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  1073. positionVectors.push(vector3);
  1074. facesOfVertices.push([]);
  1075. }
  1076. // Compute normals
  1077. var facesNormals = [];
  1078. for (index = 0; index < indices.length / 3; index++) {
  1079. var i1 = indices[index * 3];
  1080. var i2 = indices[index * 3 + 1];
  1081. var i3 = indices[index * 3 + 2];
  1082. var p1 = positionVectors[i1];
  1083. var p2 = positionVectors[i2];
  1084. var p3 = positionVectors[i3];
  1085. var p1p2 = p1.subtract(p2);
  1086. var p3p2 = p3.subtract(p2);
  1087. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  1088. facesOfVertices[i1].push(index);
  1089. facesOfVertices[i2].push(index);
  1090. facesOfVertices[i3].push(index);
  1091. }
  1092. for (index = 0; index < positionVectors.length; index++) {
  1093. var faces = facesOfVertices[index];
  1094. var normal = BABYLON.Vector3.Zero();
  1095. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  1096. normal.addInPlace(facesNormals[faces[faceIndex]]);
  1097. }
  1098. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  1099. normals[index * 3] = normal.x;
  1100. normals[index * 3 + 1] = normal.y;
  1101. normals[index * 3 + 2] = normal.z;
  1102. }
  1103. };
  1104. })();