babylon.mesh.js 40 KB

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