babylon.mesh.js 43 KB

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