babylon.mesh.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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) {
  205. if (this._vertexBuffer) {
  206. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  207. }
  208. this._uvCount = uvCount;
  209. if (updatable) {
  210. this._vertexBuffer = this._scene.getEngine().createDynamicVertexBuffer(vertices.length * 4);
  211. this._scene.getEngine().updateDynamicVertexBuffer(this._vertexBuffer, vertices);
  212. } else {
  213. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  214. }
  215. this._vertices = vertices;
  216. this._totalVertices = vertices.length / this.getFloatVertexStrideSize();
  217. this._boundingInfo = new BABYLON.BoundingInfo(vertices, this.getFloatVertexStrideSize(), 0, vertices.length);
  218. this._createGlobalSubMesh();
  219. this._positions = null;
  220. };
  221. BABYLON.Mesh.prototype.updateVertices = function (vertices) {
  222. var engine = this._scene.getEngine();
  223. engine.updateDynamicVertexBuffer(this._vertexBuffer, vertices);
  224. this._vertices = vertices;
  225. this._positions = null;
  226. };
  227. BABYLON.Mesh.prototype.setIndices = function (indices) {
  228. if (this._indexBuffer) {
  229. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  230. }
  231. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  232. this._indices = indices;
  233. this._createGlobalSubMesh();
  234. };
  235. BABYLON.Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  236. var engine = this._scene.getEngine();
  237. // Wireframe
  238. var indexToBind = this._indexBuffer;
  239. var useTriangles = true;
  240. if (wireframe) {
  241. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  242. useTriangles = false;
  243. }
  244. // VBOs
  245. engine.bindBuffers(this._vertexBuffer, indexToBind, this._vertexDeclaration, this._vertexStrideSize, effect);
  246. // Draw order
  247. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  248. };
  249. BABYLON.Mesh.prototype.render = function (subMesh) {
  250. if (!this._vertexBuffer || !this._indexBuffer) {
  251. return;
  252. }
  253. // World
  254. var world = this.getWorldMatrix();
  255. // Material
  256. var effectiveMaterial = subMesh.getMaterial();
  257. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  258. return;
  259. }
  260. effectiveMaterial._preBind();
  261. effectiveMaterial.bind(world, this);
  262. // Bind and draw
  263. var engine = this._scene.getEngine();
  264. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  265. // Unbind
  266. effectiveMaterial.unbind();
  267. };
  268. BABYLON.Mesh.prototype.isDescendantOf = function (ancestor) {
  269. if (this.parent) {
  270. if (this.parent === ancestor) {
  271. return true;
  272. }
  273. return this.parent.isDescendantOf(ancestor);
  274. }
  275. return false;
  276. };
  277. BABYLON.Mesh.prototype.getDescendants = function () {
  278. var results = [];
  279. for (var index = 0; index < this._scene.meshes.length; index++) {
  280. var mesh = this._scene.meshes[index];
  281. if (mesh.isDescendantOf(this)) {
  282. results.push(mesh);
  283. }
  284. }
  285. return results;
  286. };
  287. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  288. var results = [];
  289. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  290. var particleSystem = this._scene.particleSystems[index];
  291. if (particleSystem.emitter === this) {
  292. results.push(particleSystem);
  293. }
  294. }
  295. return results;
  296. };
  297. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  298. var results = [];
  299. var descendants = this.getDescendants();
  300. descendants.push(this);
  301. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  302. var particleSystem = this._scene.particleSystems[index];
  303. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  304. results.push(particleSystem);
  305. }
  306. }
  307. return results;
  308. };
  309. BABYLON.Mesh.prototype.getChildren = function () {
  310. var results = [];
  311. for (var index = 0; index < this._scene.meshes.length; index++) {
  312. var mesh = this._scene.meshes[index];
  313. if (mesh.parent == this) {
  314. results.push(mesh);
  315. }
  316. }
  317. return results;
  318. };
  319. BABYLON.Mesh.prototype.isInFrustrum = function (frustumPlanes) {
  320. return this._boundingInfo.isInFrustrum(frustumPlanes);
  321. };
  322. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  323. var materials = this._scene.materials;
  324. for (var index = 0; index < materials.length; index++) {
  325. if (materials[index].id == id) {
  326. this.material = materials[index];
  327. return;
  328. }
  329. }
  330. // Multi
  331. var multiMaterials = this._scene.multiMaterials;
  332. for (var index = 0; index < multiMaterials.length; index++) {
  333. if (multiMaterials[index].id == id) {
  334. this.material = multiMaterials[index];
  335. return;
  336. }
  337. }
  338. };
  339. BABYLON.Mesh.prototype.getAnimatables = function () {
  340. var results = [];
  341. if (this.material) {
  342. results.push(this.material);
  343. }
  344. return results;
  345. };
  346. // Cache
  347. BABYLON.Mesh.prototype._generatePointsArray = function () {
  348. if (this._positions)
  349. return;
  350. this._positions = [];
  351. var stride = this.getFloatVertexStrideSize();
  352. for (var index = 0; index < this._vertices.length; index += stride) {
  353. this._positions.push(BABYLON.Vector3.FromArray(this._vertices, index));
  354. }
  355. };
  356. // Collisions
  357. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  358. this._generatePointsArray();
  359. // Transformation
  360. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  361. subMesh._lastColliderTransformMatrix = transformMatrix;
  362. subMesh._lastColliderWorldVertices = [];
  363. var start = subMesh.verticesStart;
  364. var end = (subMesh.verticesStart + subMesh.verticesCount);
  365. for (var i = start; i < end; i++) {
  366. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  367. }
  368. }
  369. // Collide
  370. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  371. };
  372. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  373. for (var index = 0; index < this.subMeshes.length; index++) {
  374. var subMesh = this.subMeshes[index];
  375. // Bounding test
  376. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  377. continue;
  378. this._collideForSubMesh(subMesh, transformMatrix, collider);
  379. }
  380. };
  381. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  382. // Bounding box test
  383. if (!this._boundingInfo._checkCollision(collider))
  384. return;
  385. // Transformation matrix
  386. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  387. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  388. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  389. };
  390. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  391. if (!this._boundingInfo || !mesh._boundingInfo) {
  392. return false;
  393. }
  394. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  395. };
  396. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  397. if (!this._boundingInfo) {
  398. return false;
  399. }
  400. return this._boundingInfo.intersectsPoint(point);
  401. };
  402. // Picking
  403. BABYLON.Mesh.prototype.intersects = function (ray) {
  404. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere)) {
  405. return { hit: false, distance: 0 };
  406. }
  407. this._generatePointsArray();
  408. var distance = Number.MAX_VALUE;
  409. for (var index = 0; index < this.subMeshes.length; index++) {
  410. var subMesh = this.subMeshes[index];
  411. // Bounding test
  412. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  413. continue;
  414. var result = subMesh.intersects(ray, this._positions, this._indices);
  415. if (result.hit) {
  416. if (result.distance < distance && result.distance >= 0) {
  417. distance = result.distance;
  418. }
  419. }
  420. }
  421. if (distance >= 0)
  422. return { hit: true, distance: distance };
  423. return { hit: false, distance: 0 };
  424. };
  425. // Clone
  426. BABYLON.Mesh.prototype.clone = function (name, newParent) {
  427. var result = new BABYLON.Mesh(name, this._vertexDeclaration, this._scene);
  428. BABYLON.Tools.DeepCopy(this, result, ["name", "material"], ["_uvCount", "_vertices", "_indices", "_totalVertices"]);
  429. // Bounding info
  430. result._boundingInfo = new BABYLON.BoundingInfo(result._vertices, result.getFloatVertexStrideSize(), 0, result._vertices.length);
  431. // Material
  432. result.material = this.material;
  433. // Buffers
  434. result._vertexBuffer = this._vertexBuffer;
  435. this._vertexBuffer.references++;
  436. result._indexBuffer = this._indexBuffer;
  437. this._indexBuffer.references++;
  438. // Parent
  439. if (newParent) {
  440. result.parent = newParent;
  441. }
  442. // Children
  443. for (var index = 0; index < this._scene.meshes.length; index++) {
  444. var mesh = this._scene.meshes[index];
  445. if (mesh.parent == this) {
  446. mesh.clone(mesh.name, result);
  447. }
  448. }
  449. // Particles
  450. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  451. var system = this._scene.particleSystems[index];
  452. if (system.emitter == this) {
  453. system.clone(system.name, result);
  454. }
  455. }
  456. return result;
  457. };
  458. // Dispose
  459. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  460. if (this._vertexBuffer) {
  461. //this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  462. this._vertexBuffer = null;
  463. }
  464. if (this._indexBuffer) {
  465. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  466. this._indexBuffer = null;
  467. }
  468. // Remove from scene
  469. var index = this._scene.meshes.indexOf(this);
  470. this._scene.meshes.splice(index, 1);
  471. if (doNotRecurse) {
  472. return;
  473. }
  474. // Particles
  475. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  476. if (this._scene.particleSystems[index].emitter == this) {
  477. this._scene.particleSystems[index].dispose();
  478. index--;
  479. }
  480. }
  481. // Children
  482. var objects = this._scene.meshes.slice(0);
  483. for (var index = 0; index < objects.length; index++) {
  484. if (objects[index].parent == this) {
  485. objects[index].dispose();
  486. }
  487. }
  488. // Callback
  489. if (this.onDispose) {
  490. this.onDispose();
  491. }
  492. };
  493. // Statics
  494. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  495. var box = new BABYLON.Mesh(name, [3, 3, 2], scene);
  496. var normals = [
  497. new BABYLON.Vector3(0, 0, 1),
  498. new BABYLON.Vector3(0, 0, -1),
  499. new BABYLON.Vector3(1, 0, 0),
  500. new BABYLON.Vector3(-1, 0, 0),
  501. new BABYLON.Vector3(0, 1, 0),
  502. new BABYLON.Vector3(0, -1, 0)
  503. ];
  504. var indices = [];
  505. var vertices = [];
  506. // Create each face in turn.
  507. for (var index = 0; index < normals.length; index++) {
  508. var normal = normals[index];
  509. // Get two vectors perpendicular to the face normal and to each other.
  510. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  511. var side2 = BABYLON.Vector3.Cross(normal, side1);
  512. // Six indices (two triangles) per face.
  513. var verticesLength = vertices.length / 8;
  514. indices.push(verticesLength);
  515. indices.push(verticesLength + 1);
  516. indices.push(verticesLength + 2);
  517. indices.push(verticesLength);
  518. indices.push(verticesLength + 2);
  519. indices.push(verticesLength + 3);
  520. // Four vertices per face.
  521. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  522. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 1.0, 1.0);
  523. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  524. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 0.0, 1.0);
  525. vertex = normal.add(side1).add(side2).scale(size / 2);
  526. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 0.0, 0.0);
  527. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  528. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 1.0, 0.0);
  529. }
  530. box.setVertices(vertices, 1, updatable);
  531. box.setIndices(indices);
  532. return box;
  533. };
  534. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  535. var sphere = new BABYLON.Mesh(name, [3, 3, 2], scene);
  536. var radius = diameter / 2;
  537. var totalZRotationSteps = 2 + segments;
  538. var totalYRotationSteps = 2 * totalZRotationSteps;
  539. var indices = [];
  540. var vertices = [];
  541. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  542. var normalizedZ = zRotationStep / totalZRotationSteps;
  543. var angleZ = (normalizedZ * Math.PI);
  544. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  545. var normalizedY = yRotationStep / totalYRotationSteps;
  546. var angleY = normalizedY * Math.PI * 2;
  547. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  548. var rotationY = BABYLON.Matrix.RotationY(angleY);
  549. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  550. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  551. var vertex = complete.scale(radius);
  552. var normal = BABYLON.Vector3.Normalize(vertex);
  553. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, normalizedZ, normalizedY);
  554. }
  555. if (zRotationStep > 0) {
  556. var verticesCount = vertices.length / 8;
  557. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  558. indices.push((firstIndex));
  559. indices.push((firstIndex + 1));
  560. indices.push(firstIndex + totalYRotationSteps + 1);
  561. indices.push((firstIndex + totalYRotationSteps + 1));
  562. indices.push((firstIndex + 1));
  563. indices.push((firstIndex + totalYRotationSteps + 2));
  564. }
  565. }
  566. }
  567. sphere.setVertices(vertices, 1, updatable);
  568. sphere.setIndices(indices);
  569. return sphere;
  570. };
  571. // Cylinder (Code from SharpDX.org)
  572. BABYLON.Mesh.CreateCylinder = function (name, height, diameter, tessellation, scene, updatable) {
  573. var radius = diameter / 2;
  574. var indices = [];
  575. var vertices = [];
  576. var cylinder = new BABYLON.Mesh(name, [3, 3, 2], scene);
  577. var getCircleVector = function (i) {
  578. var angle = (i * 2.0 * Math.PI / tessellation);
  579. var dx = Math.sin(angle);
  580. var dz = Math.cos(angle);
  581. return new BABYLON.Vector3(dx, 0, dz);
  582. };
  583. var createCylinderCap = function (isTop) {
  584. // Create cap indices.
  585. for (var i = 0; i < tessellation - 2; i++) {
  586. var i1 = (i + 1) % tessellation;
  587. var i2 = (i + 2) % tessellation;
  588. if (isTop) {
  589. var tmp = i1;
  590. var i1 = i2;
  591. i2 = tmp;
  592. }
  593. var vbase = vertices.length / cylinder.getFloatVertexStrideSize();
  594. indices.push(vbase);
  595. indices.push(vbase + i1);
  596. indices.push(vbase + i2);
  597. }
  598. // Which end of the cylinder is this?
  599. var normal = new BABYLON.Vector3(0, 1, 0);
  600. var textureScale = new BABYLON.Vector2(-0.5, -0.5);
  601. if (!isTop) {
  602. normal = normal.scale(-1);
  603. textureScale.x = -textureScale.x;
  604. }
  605. // Create cap vertices.
  606. for (var i = 0; i < tessellation; i++) {
  607. var circleVector = getCircleVector(i);
  608. var position = circleVector.scale(radius).add(normal.scale(height));
  609. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  610. vertices.push(
  611. position.x, position.y, position.z,
  612. normal.x, normal.y, normal.z,
  613. textureCoordinate.x, textureCoordinate.y
  614. );
  615. }
  616. };
  617. height /= 2;
  618. var topOffset = new BABYLON.Vector3(0, 1, 0).scale(height);
  619. var stride = tessellation + 1;
  620. // Create a ring of triangles around the outside of the cylinder.
  621. for (var i = 0; i <= tessellation; i++)
  622. {
  623. var normal = getCircleVector(i);
  624. var sideOffset = normal.scale(radius);
  625. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  626. var position = sideOffset.add(topOffset);
  627. vertices.push(
  628. position.x, position.y, position.z,
  629. normal.x, normal.y, normal.z,
  630. textureCoordinate.x, textureCoordinate.y
  631. );
  632. position = sideOffset.subtract(topOffset);
  633. textureCoordinate.y += 1;
  634. vertices.push(
  635. position.x, position.y, position.z,
  636. normal.x, normal.y, normal.z,
  637. textureCoordinate.x, textureCoordinate.y
  638. );
  639. indices.push(i * 2);
  640. indices.push((i * 2 + 2) % (stride * 2));
  641. indices.push(i * 2 + 1);
  642. indices.push(i * 2 + 1);
  643. indices.push((i * 2 + 2) % (stride * 2));
  644. indices.push((i * 2 + 3) % (stride * 2));
  645. }
  646. // Create flat triangle fan caps to seal the top and bottom.
  647. createCylinderCap(true);
  648. createCylinderCap(false);
  649. cylinder.setVertices(vertices, 1, updatable);
  650. cylinder.setIndices(indices);
  651. return cylinder;
  652. };
  653. // Torus (Code from SharpDX.org)
  654. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  655. var torus = new BABYLON.Mesh(name, [3, 3, 2], scene);
  656. var indices = [];
  657. var vertices = [];
  658. var stride = tessellation + 1;
  659. for (var i = 0; i <= tessellation; i++) {
  660. var u = i / tessellation;
  661. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  662. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  663. for (var j = 0; j <= tessellation; j++) {
  664. var v = 1 - j / tessellation;
  665. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  666. var dx = Math.cos(innerAngle);
  667. var dy = Math.sin(innerAngle);
  668. // Create a vertex.
  669. var normal = new BABYLON.Vector3(dx, dy, 0);
  670. var position = normal.scale(thickness / 2);
  671. var textureCoordinate = new BABYLON.Vector2(u, v);
  672. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  673. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  674. vertices.push(
  675. position.x, position.y, position.z,
  676. normal.x, normal.y, normal.z,
  677. textureCoordinate.x, textureCoordinate.y
  678. );
  679. // And create indices for two triangles.
  680. var nextI = (i + 1) % stride;
  681. var nextJ = (j + 1) % stride;
  682. indices.push(i * stride + j);
  683. indices.push(i * stride + nextJ);
  684. indices.push(nextI * stride + j);
  685. indices.push(i * stride + nextJ);
  686. indices.push(nextI * stride + nextJ);
  687. indices.push(nextI * stride + j);
  688. }
  689. }
  690. torus.setVertices(vertices, 1, updatable);
  691. torus.setIndices(indices);
  692. return torus;
  693. };
  694. // Plane
  695. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  696. var plane = new BABYLON.Mesh(name, [3, 3, 2], scene);
  697. var indices = [];
  698. var vertices = [];
  699. // Vertices
  700. var halfSize = size / 2.0;
  701. vertices.push(-halfSize, -halfSize, 0, 0, 0, -1.0, 0.0, 0.0);
  702. vertices.push(halfSize, -halfSize, 0, 0, 0, -1.0, 1.0, 0.0);
  703. vertices.push(halfSize, halfSize, 0, 0, 0, -1.0, 1.0, 1.0);
  704. vertices.push(-halfSize, halfSize, 0, 0, 0, -1.0, 0.0, 1.0);
  705. // Indices
  706. indices.push(0);
  707. indices.push(1);
  708. indices.push(2);
  709. indices.push(0);
  710. indices.push(2);
  711. indices.push(3);
  712. plane.setVertices(vertices, 1, updatable);
  713. plane.setIndices(indices);
  714. return plane;
  715. };
  716. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  717. var ground = new BABYLON.Mesh(name, [3, 3, 2], scene);
  718. var indices = [];
  719. var vertices = [];
  720. var row, col;
  721. for (row = 0; row <= subdivisions; row++) {
  722. for (col = 0; col <= subdivisions; col++) {
  723. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  724. var normal = new BABYLON.Vector3(0, 1.0, 0);
  725. vertices.push(position.x, position.y, position.z,
  726. normal.x, normal.y, normal.z,
  727. col / subdivisions, 1.0 - row / subdivisions);
  728. }
  729. }
  730. for (row = 0; row < subdivisions; row++) {
  731. for (col = 0; col < subdivisions; col++) {
  732. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  733. indices.push(col + 1 + row * (subdivisions + 1));
  734. indices.push(col + row * (subdivisions + 1));
  735. indices.push(col + (row + 1) * (subdivisions + 1));
  736. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  737. indices.push(col + row * (subdivisions + 1));
  738. }
  739. }
  740. ground.setVertices(vertices, 1, updatable);
  741. ground.setIndices(indices);
  742. return ground;
  743. };
  744. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  745. var ground = new BABYLON.Mesh(name, [3, 3, 2], scene);
  746. var img = new Image();
  747. img.onload = function () {
  748. var indices = [];
  749. var vertices = [];
  750. var row, col;
  751. // Getting height map data
  752. var canvas = document.createElement("canvas");
  753. var context = canvas.getContext("2d");
  754. var heightMapWidth = img.width;
  755. var heightMapHeight = img.height;
  756. canvas.width = heightMapWidth;
  757. canvas.height = heightMapHeight;
  758. context.drawImage(img, 0, 0);
  759. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  760. // Vertices
  761. for (row = 0; row <= subdivisions; row++) {
  762. for (col = 0; col <= subdivisions; col++) {
  763. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  764. // Compute height
  765. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  766. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  767. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  768. var r = buffer[pos] / 255.0;
  769. var g = buffer[pos + 1] / 255.0;
  770. var b = buffer[pos + 2] / 255.0;
  771. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  772. position.y = minHeight + (maxHeight - minHeight) * gradient;
  773. // Add vertex
  774. vertices.push(position.x, position.y, position.z,
  775. 0, 0, 0,
  776. col / subdivisions, 1.0 - row / subdivisions);
  777. }
  778. }
  779. // Indices
  780. for (row = 0; row < subdivisions; row++) {
  781. for (col = 0; col < subdivisions; col++) {
  782. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  783. indices.push(col + 1 + row * (subdivisions + 1));
  784. indices.push(col + row * (subdivisions + 1));
  785. indices.push(col + (row + 1) * (subdivisions + 1));
  786. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  787. indices.push(col + row * (subdivisions + 1));
  788. }
  789. }
  790. // Normals
  791. BABYLON.Mesh.ComputeNormal(vertices, indices, ground.getFloatVertexStrideSize());
  792. // Transfer
  793. ground.setVertices(vertices, 1, updatable);
  794. ground.setIndices(indices);
  795. ground._isReady = true;
  796. };
  797. img.src = url;
  798. ground._isReady = false;
  799. return ground;
  800. };
  801. // Tools
  802. BABYLON.Mesh.ComputeNormal = function (vertices, indices, stride, normalOffset) {
  803. var positions = [];
  804. var facesOfVertices = [];
  805. var index;
  806. if (normalOffset === undefined) {
  807. normalOffset = 3;
  808. }
  809. for (index = 0; index < vertices.length; index += stride) {
  810. var position = new BABYLON.Vector3(vertices[index], vertices[index + 1], vertices[index + 2]);
  811. positions.push(position);
  812. facesOfVertices.push([]);
  813. }
  814. // Compute normals
  815. var facesNormals = [];
  816. for (index = 0; index < indices.length / 3; index++) {
  817. var i1 = indices[index * 3];
  818. var i2 = indices[index * 3 + 1];
  819. var i3 = indices[index * 3 + 2];
  820. var p1 = positions[i1];
  821. var p2 = positions[i2];
  822. var p3 = positions[i3];
  823. var p1p2 = p1.subtract(p2);
  824. var p3p2 = p3.subtract(p2);
  825. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  826. facesOfVertices[i1].push(index);
  827. facesOfVertices[i2].push(index);
  828. facesOfVertices[i3].push(index);
  829. }
  830. for (index = 0; index < positions.length; index++) {
  831. var faces = facesOfVertices[index];
  832. var normal = BABYLON.Vector3.Zero();
  833. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  834. normal.addInPlace(facesNormals[faces[faceIndex]]);
  835. }
  836. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  837. vertices[index * stride + normalOffset] = normal.x;
  838. vertices[index * stride + normalOffset + 1] = normal.y;
  839. vertices[index * stride + normalOffset + 2] = normal.z;
  840. }
  841. };
  842. })();