babylon.mesh.js 38 KB

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