babylon.mesh.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. "use strict";
  2. var BABYLON = BABYLON || {};
  3. (function () {
  4. BABYLON.Mesh = function (name, scene) {
  5. BABYLON.Node.call(this, scene);
  6. this.name = name;
  7. this.id = name;
  8. this._totalVertices = 0;
  9. this._worldMatrix = BABYLON.Matrix.Identity();
  10. scene.meshes.push(this);
  11. this.position = new BABYLON.Vector3(0, 0, 0);
  12. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13. this.rotationQuaternion = null;
  14. this.scaling = new BABYLON.Vector3(1, 1, 1);
  15. this._pivotMatrix = BABYLON.Matrix.Identity();
  16. this._indices = [];
  17. this.subMeshes = [];
  18. this._renderId = 0;
  19. this._onBeforeRenderCallbacks = [];
  20. // Animations
  21. this.animations = [];
  22. // Cache
  23. this._positions = null;
  24. BABYLON.Mesh.prototype._initCache.call(this);
  25. this._localScaling = BABYLON.Matrix.Zero();
  26. this._localRotation = BABYLON.Matrix.Zero();
  27. this._localTranslation = BABYLON.Matrix.Zero();
  28. this._localBillboard = BABYLON.Matrix.Zero();
  29. this._localPivotScaling = BABYLON.Matrix.Zero();
  30. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  31. this._localWorld = BABYLON.Matrix.Zero();
  32. this._worldMatrix = BABYLON.Matrix.Zero();
  33. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  34. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  35. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  36. this._absolutePosition = BABYLON.Vector3.Zero();
  37. };
  38. BABYLON.Mesh.prototype = Object.create(BABYLON.Node.prototype);
  39. // Constants
  40. BABYLON.Mesh.BILLBOARDMODE_NONE = 0;
  41. BABYLON.Mesh.BILLBOARDMODE_X = 1;
  42. BABYLON.Mesh.BILLBOARDMODE_Y = 2;
  43. BABYLON.Mesh.BILLBOARDMODE_Z = 4;
  44. BABYLON.Mesh.BILLBOARDMODE_ALL = 7;
  45. // Members
  46. BABYLON.Mesh.prototype.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  47. BABYLON.Mesh.prototype.material = null;
  48. BABYLON.Mesh.prototype.isVisible = true;
  49. BABYLON.Mesh.prototype.isPickable = true;
  50. BABYLON.Mesh.prototype.visibility = 1.0;
  51. BABYLON.Mesh.prototype.billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  52. BABYLON.Mesh.prototype.checkCollisions = false;
  53. BABYLON.Mesh.prototype.receiveShadows = false;
  54. BABYLON.Mesh.prototype._isDisposed = false;
  55. BABYLON.Mesh.prototype.onDispose = null;
  56. BABYLON.Mesh.prototype.skeleton = null;
  57. BABYLON.Mesh.prototype.renderingGroupId = 0;
  58. BABYLON.Mesh.prototype.infiniteDistance = false;
  59. // Properties
  60. BABYLON.Mesh.prototype.getBoundingInfo = function () {
  61. return this._boundingInfo;
  62. };
  63. BABYLON.Mesh.prototype.getScene = function () {
  64. return this._scene;
  65. };
  66. BABYLON.Mesh.prototype.getWorldMatrix = function () {
  67. if (this._currentRenderId !== this._scene.getRenderId()) {
  68. this.computeWorldMatrix();
  69. }
  70. return this._worldMatrix;
  71. };
  72. BABYLON.Mesh.prototype.getAbsolutePosition = function () {
  73. this.computeWorldMatrix();
  74. return this._absolutePosition;
  75. };
  76. BABYLON.Mesh.prototype.setAbsolutePosition = function (absolutePosition) {
  77. if (!absolutePosition) {
  78. return;
  79. }
  80. var absolutePositionX;
  81. var absolutePositionY;
  82. var absolutePositionZ;
  83. if (absolutePosition.x === undefined) {
  84. if (arguments.length < 3) {
  85. return;
  86. }
  87. absolutePositionX = arguments[0];
  88. absolutePositionY = arguments[1];
  89. absolutePositionZ = arguments[2];
  90. }
  91. else {
  92. absolutePositionX = absolutePosition.x;
  93. absolutePositionY = absolutePosition.y;
  94. absolutePositionZ = absolutePosition.z;
  95. }
  96. // worldMatrix = pivotMatrix * scalingMatrix * rotationMatrix * translateMatrix * parentWorldMatrix
  97. // => translateMatrix = invertRotationMatrix * invertScalingMatrix * invertPivotMatrix * worldMatrix * invertParentWorldMatrix
  98. // get this matrice before the other ones since
  99. // that will update them if they have to be updated
  100. var worldMatrix = this.getWorldMatrix().clone();
  101. worldMatrix.m[12] = absolutePositionX;
  102. worldMatrix.m[13] = absolutePositionY;
  103. worldMatrix.m[14] = absolutePositionZ;
  104. var invertRotationMatrix = this._localRotation.clone();
  105. invertRotationMatrix.invert();
  106. var invertScalingMatrix = this._localScaling.clone();
  107. invertScalingMatrix.invert();
  108. var invertPivotMatrix = this._pivotMatrix.clone();
  109. invertPivotMatrix.invert();
  110. var translateMatrix = invertRotationMatrix.multiply(invertScalingMatrix);
  111. translateMatrix.multiplyToRef(invertPivotMatrix, invertScalingMatrix); // reuse matrix
  112. invertScalingMatrix.multiplyToRef(worldMatrix, translateMatrix);
  113. if (this.parent) {
  114. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  115. invertParentWorldMatrix.invert();
  116. translateMatrix.multiplyToRef(invertParentWorldMatrix, invertScalingMatrix); // reuse matrix
  117. translateMatrix = invertScalingMatrix;
  118. }
  119. this.position.x = translateMatrix.m[12];
  120. this.position.y = translateMatrix.m[13];
  121. this.position.z = translateMatrix.m[14];
  122. };
  123. BABYLON.Mesh.prototype.getTotalVertices = function () {
  124. return this._totalVertices;
  125. };
  126. BABYLON.Mesh.prototype.getVerticesData = function (kind) {
  127. return this._vertexBuffers[kind].getData();
  128. };
  129. BABYLON.Mesh.prototype.getVertexBuffer = function (kind) {
  130. return this._vertexBuffers[kind];
  131. };
  132. BABYLON.Mesh.prototype.isVerticesDataPresent = function (kind) {
  133. if (!this._vertexBuffers) {
  134. if (this._delayInfo) {
  135. return this._delayInfo.indexOf(kind) !== -1;
  136. }
  137. return false;
  138. }
  139. return this._vertexBuffers[kind] !== undefined;
  140. };
  141. BABYLON.Mesh.prototype.getVerticesDataKinds = function () {
  142. var result = [];
  143. if (!this._vertexBuffers && this._delayInfo) {
  144. for (var kind in this._delayInfo) {
  145. result.push(kind);
  146. }
  147. } else {
  148. for (var kind in this._vertexBuffers) {
  149. result.push(kind);
  150. }
  151. }
  152. return result;
  153. };
  154. BABYLON.Mesh.prototype.getTotalIndices = function () {
  155. return this._indices.length;
  156. };
  157. BABYLON.Mesh.prototype.getIndices = function () {
  158. return this._indices;
  159. };
  160. BABYLON.Mesh.prototype.getVertexStrideSize = function () {
  161. return this._vertexStrideSize;
  162. };
  163. BABYLON.Mesh.prototype.setPivotMatrix = function (matrix) {
  164. this._pivotMatrix = matrix;
  165. this._cache.pivotMatrixUpdated = true;
  166. };
  167. BABYLON.Mesh.prototype.getPivotMatrix = function () {
  168. return this._pivotMatrix;
  169. };
  170. BABYLON.Mesh.prototype._isSynchronized = function () {
  171. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE)
  172. return false;
  173. if (this._cache.pivotMatrixUpdated) {
  174. return false;
  175. }
  176. if (this.infiniteDistance) {
  177. return false;
  178. }
  179. if (!this._cache.position.equals(this.position))
  180. return false;
  181. if (this.rotationQuaternion) {
  182. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  183. return false;
  184. } else {
  185. if (!this._cache.rotation.equals(this.rotation))
  186. return false;
  187. }
  188. if (!this._cache.scaling.equals(this.scaling))
  189. return false;
  190. return true;
  191. };
  192. BABYLON.Mesh.prototype.isReady = function () {
  193. return this._isReady;
  194. };
  195. BABYLON.Mesh.prototype.isAnimated = function () {
  196. return this._animationStarted;
  197. };
  198. BABYLON.Mesh.prototype.isDisposed = function () {
  199. return this._isDisposed;
  200. };
  201. // Methods
  202. BABYLON.Mesh.prototype._initCache = function () {
  203. this._cache.localMatrixUpdated = false;
  204. this._cache.position = BABYLON.Vector3.Zero();
  205. this._cache.scaling = BABYLON.Vector3.Zero();
  206. this._cache.rotation = BABYLON.Vector3.Zero();
  207. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  208. };
  209. BABYLON.Mesh.prototype.markAsDirty = function (property) {
  210. if (property === "rotation") {
  211. this.rotationQuaternion = null;
  212. }
  213. this._syncChildFlag();
  214. };
  215. BABYLON.Mesh.prototype.refreshBoundingInfo = function () {
  216. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  217. if (!data) {
  218. return;
  219. }
  220. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  221. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  222. for (var index = 0; index < this.subMeshes.length; index++) {
  223. this.subMeshes[index].refreshBoundingInfo();
  224. }
  225. this._updateBoundingInfo();
  226. };
  227. BABYLON.Mesh.prototype._updateBoundingInfo = function () {
  228. if (this._boundingInfo) {
  229. this._scaleFactor = Math.max(this.scaling.x, this.scaling.y);
  230. this._scaleFactor = Math.max(this._scaleFactor, this.scaling.z);
  231. if (this.parent && this.parent._scaleFactor)
  232. this._scaleFactor = this._scaleFactor * this.parent._scaleFactor;
  233. this._boundingInfo._update(this._worldMatrix, this._scaleFactor);
  234. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  235. var subMesh = this.subMeshes[subIndex];
  236. subMesh.updateBoundingInfo(this._worldMatrix, this._scaleFactor);
  237. }
  238. }
  239. };
  240. BABYLON.Mesh.prototype.computeWorldMatrix = function (force) {
  241. if (!force && (this._currentRenderId == this._scene.getRenderId() || this.isSynchronized(true))) {
  242. return this._worldMatrix;
  243. }
  244. this._syncChildFlag();
  245. this._cache.position.copyFrom(this.position);
  246. this._cache.scaling.copyFrom(this.scaling);
  247. this._cache.pivotMatrixUpdated = false;
  248. this._currentRenderId = this._scene.getRenderId();
  249. // Scaling
  250. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  251. // Rotation
  252. if (this.rotationQuaternion) {
  253. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  254. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  255. } else {
  256. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  257. this._cache.rotation.copyFrom(this.rotation);
  258. }
  259. // Translation
  260. if (this.infiniteDistance) {
  261. var camera = this._scene.activeCamera;
  262. BABYLON.Matrix.TranslationToRef(this.position.x + camera.position.x, this.position.y + camera.position.y, this.position.z + camera.position.z, this._localTranslation);
  263. } else {
  264. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  265. }
  266. // Composing transformations
  267. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  268. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  269. // Billboarding
  270. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE) {
  271. var localPosition = this.position.clone();
  272. var zero = this._scene.activeCamera.position.clone();
  273. if (this.parent && this.parent.position) {
  274. localPosition.addInPlace(this.parent.position);
  275. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  276. }
  277. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_ALL === BABYLON.Mesh.BILLBOARDMODE_ALL) {
  278. zero = this._scene.activeCamera.position;
  279. } else {
  280. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  281. zero.x = localPosition.x + BABYLON.Engine.epsilon;
  282. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  283. zero.y = localPosition.y + BABYLON.Engine.epsilon;
  284. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  285. zero.z = localPosition.z + BABYLON.Engine.epsilon;
  286. }
  287. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  288. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  289. this._localBillboard.invert();
  290. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  291. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  292. }
  293. // Local world
  294. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  295. // Parent
  296. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  297. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  298. } else {
  299. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._worldMatrix);
  300. }
  301. // Bounding info
  302. this._updateBoundingInfo();
  303. // Absolute position
  304. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  305. return this._worldMatrix;
  306. };
  307. BABYLON.Mesh.prototype._createGlobalSubMesh = function () {
  308. if (!this._totalVertices || !this._indices) {
  309. return null;
  310. }
  311. this.subMeshes = [];
  312. return new BABYLON.SubMesh(0, 0, this._totalVertices, 0, this._indices.length, this);
  313. };
  314. BABYLON.Mesh.prototype.subdivide = function (count) {
  315. if (count < 1) {
  316. return;
  317. }
  318. var subdivisionSize = this._indices.length / count;
  319. var offset = 0;
  320. this.subMeshes = [];
  321. for (var index = 0; index < count; index++) {
  322. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, this._indices.length - offset), this);
  323. offset += subdivisionSize;
  324. }
  325. };
  326. BABYLON.Mesh.prototype.setVerticesData = function (data, kind, updatable) {
  327. if (!this._vertexBuffers) {
  328. this._vertexBuffers = {};
  329. }
  330. if (this._vertexBuffers[kind]) {
  331. this._vertexBuffers[kind].dispose();
  332. }
  333. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this, data, kind, updatable);
  334. if (kind === BABYLON.VertexBuffer.PositionKind) {
  335. var stride = this._vertexBuffers[kind].getStrideSize();
  336. this._totalVertices = data.length / stride;
  337. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  338. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  339. this._createGlobalSubMesh();
  340. }
  341. };
  342. BABYLON.Mesh.prototype.updateVerticesData = function (kind, data) {
  343. if (this._vertexBuffers[kind]) {
  344. this._vertexBuffers[kind].update(data);
  345. }
  346. };
  347. BABYLON.Mesh.prototype.setIndices = function (indices) {
  348. if (this._indexBuffer) {
  349. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  350. }
  351. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  352. this._indices = indices;
  353. this._createGlobalSubMesh();
  354. };
  355. BABYLON.Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  356. var engine = this._scene.getEngine();
  357. // Wireframe
  358. var indexToBind = this._indexBuffer;
  359. var useTriangles = true;
  360. if (wireframe) {
  361. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  362. useTriangles = false;
  363. }
  364. // VBOs
  365. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  366. // Draw order
  367. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  368. };
  369. BABYLON.Mesh.prototype.registerBeforeRender = function (func) {
  370. this._onBeforeRenderCallbacks.push(func);
  371. };
  372. BABYLON.Mesh.prototype.unregisterBeforeRender = function (func) {
  373. var index = this._onBeforeRenderCallbacks.indexOf(func);
  374. if (index > -1) {
  375. this._onBeforeRenderCallbacks.splice(index, 1);
  376. }
  377. };
  378. BABYLON.Mesh.prototype.render = function (subMesh) {
  379. if (!this._vertexBuffers || !this._indexBuffer) {
  380. return;
  381. }
  382. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  383. this._onBeforeRenderCallbacks[callbackIndex]();
  384. }
  385. // World
  386. var world = this.getWorldMatrix();
  387. // Material
  388. var effectiveMaterial = subMesh.getMaterial();
  389. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  390. return;
  391. }
  392. effectiveMaterial._preBind();
  393. effectiveMaterial.bind(world, this);
  394. // Bind and draw
  395. var engine = this._scene.getEngine();
  396. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  397. // Unbind
  398. effectiveMaterial.unbind();
  399. };
  400. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  401. var results = [];
  402. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  403. var particleSystem = this._scene.particleSystems[index];
  404. if (particleSystem.emitter === this) {
  405. results.push(particleSystem);
  406. }
  407. }
  408. return results;
  409. };
  410. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  411. var results = [];
  412. var descendants = this.getDescendants();
  413. descendants.push(this);
  414. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  415. var particleSystem = this._scene.particleSystems[index];
  416. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  417. results.push(particleSystem);
  418. }
  419. }
  420. return results;
  421. };
  422. BABYLON.Mesh.prototype.getChildren = function () {
  423. var results = [];
  424. for (var index = 0; index < this._scene.meshes.length; index++) {
  425. var mesh = this._scene.meshes[index];
  426. if (mesh.parent == this) {
  427. results.push(mesh);
  428. }
  429. }
  430. return results;
  431. };
  432. BABYLON.Mesh.prototype.isInFrustum = function (frustumPlanes) {
  433. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  434. return false;
  435. }
  436. var result = this._boundingInfo.isInFrustum(frustumPlanes);
  437. if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  438. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  439. var that = this;
  440. this._scene._addPendingData(this);
  441. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  442. BABYLON.SceneLoader._ImportGeometry(JSON.parse(data), that);
  443. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  444. that._scene._removePendingData(that);
  445. }, function () { }, this._scene.database);
  446. }
  447. return result;
  448. };
  449. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  450. var materials = this._scene.materials;
  451. for (var index = 0; index < materials.length; index++) {
  452. if (materials[index].id == id) {
  453. this.material = materials[index];
  454. return;
  455. }
  456. }
  457. // Multi
  458. var multiMaterials = this._scene.multiMaterials;
  459. for (var index = 0; index < multiMaterials.length; index++) {
  460. if (multiMaterials[index].id == id) {
  461. this.material = multiMaterials[index];
  462. return;
  463. }
  464. }
  465. };
  466. BABYLON.Mesh.prototype.getAnimatables = function () {
  467. var results = [];
  468. if (this.material) {
  469. results.push(this.material);
  470. }
  471. return results;
  472. };
  473. // Geometry
  474. // Deprecated: use setPositionWithLocalVector instead
  475. BABYLON.Mesh.prototype.setLocalTranslation = function (vector3) {
  476. console.warn("deprecated: use setPositionWithLocalVector instead");
  477. this.computeWorldMatrix();
  478. var worldMatrix = this._worldMatrix.clone();
  479. worldMatrix.setTranslation(BABYLON.Vector3.Zero());
  480. this.position = BABYLON.Vector3.TransformCoordinates(vector3, worldMatrix);
  481. };
  482. // Deprecated: use getPositionExpressedInLocalSpace instead
  483. BABYLON.Mesh.prototype.getLocalTranslation = function () {
  484. console.warn("deprecated: use getPositionExpressedInLocalSpace instead");
  485. this.computeWorldMatrix();
  486. var invWorldMatrix = this._worldMatrix.clone();
  487. invWorldMatrix.setTranslation(BABYLON.Vector3.Zero());
  488. invWorldMatrix.invert();
  489. return BABYLON.Vector3.TransformCoordinates(this.position, invWorldMatrix);
  490. };
  491. BABYLON.Mesh.prototype.setPositionWithLocalVector = function (vector3) {
  492. this.computeWorldMatrix();
  493. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  494. };
  495. BABYLON.Mesh.prototype.getPositionExpressedInLocalSpace = function () {
  496. this.computeWorldMatrix();
  497. var invLocalWorldMatrix = this._localWorld.clone();
  498. invLocalWorldMatrix.invert();
  499. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  500. };
  501. BABYLON.Mesh.prototype.locallyTranslate = function (vector3) {
  502. this.computeWorldMatrix();
  503. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  504. };
  505. BABYLON.Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  506. // Position
  507. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  508. return;
  509. }
  510. this._resetPointsArrayCache();
  511. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  512. var temp = new BABYLON.MatrixType(data.length);
  513. for (var index = 0; index < data.length; index += 3) {
  514. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  515. }
  516. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].isUpdatable());
  517. // Normals
  518. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  519. return;
  520. }
  521. data = this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].getData();
  522. for (var index = 0; index < data.length; index += 3) {
  523. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  524. }
  525. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].isUpdatable());
  526. };
  527. BABYLON.Mesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  528. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  529. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  530. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  531. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  532. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  533. /// <returns>Mesh oriented towards targetMesh</returns>
  534. yawCor = yawCor || 0; // default to zero if undefined
  535. pitchCor = pitchCor || 0;
  536. rollCor = rollCor || 0;
  537. var dv = targetPoint.subtract(this.position);
  538. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  539. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  540. var pitch = Math.atan2(dv.y, len);
  541. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  542. };
  543. // Cache
  544. BABYLON.Mesh.prototype._resetPointsArrayCache = function () {
  545. this._positions = null;
  546. };
  547. BABYLON.Mesh.prototype._generatePointsArray = function () {
  548. if (this._positions)
  549. return;
  550. this._positions = [];
  551. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  552. for (var index = 0; index < data.length; index += 3) {
  553. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  554. }
  555. };
  556. // Collisions
  557. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  558. this._generatePointsArray();
  559. // Transformation
  560. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  561. subMesh._lastColliderTransformMatrix = transformMatrix;
  562. subMesh._lastColliderWorldVertices = [];
  563. var start = subMesh.verticesStart;
  564. var end = (subMesh.verticesStart + subMesh.verticesCount);
  565. for (var i = start; i < end; i++) {
  566. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  567. }
  568. }
  569. // Collide
  570. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  571. };
  572. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  573. for (var index = 0; index < this.subMeshes.length; index++) {
  574. var subMesh = this.subMeshes[index];
  575. // Bounding test
  576. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  577. continue;
  578. this._collideForSubMesh(subMesh, transformMatrix, collider);
  579. }
  580. };
  581. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  582. // Bounding box test
  583. if (!this._boundingInfo._checkCollision(collider))
  584. return;
  585. // Transformation matrix
  586. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  587. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  588. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  589. };
  590. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  591. if (!this._boundingInfo || !mesh._boundingInfo) {
  592. return false;
  593. }
  594. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  595. };
  596. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  597. if (!this._boundingInfo) {
  598. return false;
  599. }
  600. return this._boundingInfo.intersectsPoint(point);
  601. };
  602. // Picking
  603. BABYLON.Mesh.prototype.intersects = function (ray, fastCheck) {
  604. var pickingInfo = new BABYLON.PickingInfo();
  605. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  606. return pickingInfo;
  607. }
  608. this._generatePointsArray();
  609. var distance = Number.MAX_VALUE;
  610. for (var index = 0; index < this.subMeshes.length; index++) {
  611. var subMesh = this.subMeshes[index];
  612. // Bounding test
  613. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  614. continue;
  615. var currentDistance = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  616. if (currentDistance > 0) {
  617. if (fastCheck || currentDistance < distance) {
  618. distance = currentDistance;
  619. if (fastCheck) {
  620. break;
  621. }
  622. }
  623. }
  624. }
  625. if (distance >= 0 && distance < Number.MAX_VALUE) {
  626. // Get picked point
  627. var world = this.getWorldMatrix();
  628. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  629. var direction = ray.direction.clone();
  630. direction.normalize();
  631. direction = direction.scale(distance);
  632. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  633. var pickedPoint = worldOrigin.add(worldDirection);
  634. // Return result
  635. pickingInfo.hit = true;
  636. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  637. pickingInfo.pickedPoint = pickedPoint;
  638. pickingInfo.pickedMesh = this;
  639. return pickingInfo;
  640. }
  641. return pickingInfo;
  642. };
  643. // Clone
  644. BABYLON.Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  645. var result = new BABYLON.Mesh(name, this._scene);
  646. // Buffers
  647. result._vertexBuffers = this._vertexBuffers;
  648. for (var kind in result._vertexBuffers) {
  649. result._vertexBuffers[kind].references++;
  650. }
  651. result._indexBuffer = this._indexBuffer;
  652. this._indexBuffer.references++;
  653. // Deep copy
  654. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  655. // Bounding info
  656. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  657. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  658. // Material
  659. result.material = this.material;
  660. // Parent
  661. if (newParent) {
  662. result.parent = newParent;
  663. }
  664. if (!doNotCloneChildren) {
  665. // Children
  666. for (var index = 0; index < this._scene.meshes.length; index++) {
  667. var mesh = this._scene.meshes[index];
  668. if (mesh.parent == this) {
  669. mesh.clone(mesh.name, result);
  670. }
  671. }
  672. }
  673. // Particles
  674. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  675. var system = this._scene.particleSystems[index];
  676. if (system.emitter == this) {
  677. system.clone(system.name, result);
  678. }
  679. }
  680. result.computeWorldMatrix(true);
  681. return result;
  682. };
  683. // Dispose
  684. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  685. if (this._vertexBuffers) {
  686. for (var index = 0; index < this._vertexBuffers.length; index++) {
  687. this._vertexBuffers[index].dispose();
  688. }
  689. this._vertexBuffers = null;
  690. }
  691. if (this._indexBuffer) {
  692. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  693. this._indexBuffer = null;
  694. }
  695. // Remove from scene
  696. var index = this._scene.meshes.indexOf(this);
  697. this._scene.meshes.splice(index, 1);
  698. if (!doNotRecurse) {
  699. // Particles
  700. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  701. if (this._scene.particleSystems[index].emitter == this) {
  702. this._scene.particleSystems[index].dispose();
  703. index--;
  704. }
  705. }
  706. // Children
  707. var objects = this._scene.meshes.slice(0);
  708. for (var index = 0; index < objects.length; index++) {
  709. if (objects[index].parent == this) {
  710. objects[index].dispose();
  711. }
  712. }
  713. } else {
  714. for (var index = 0; index < this._scene.meshes.length; index++) {
  715. var obj = this._scene.meshes[index];
  716. if (obj.parent === this) {
  717. obj.parent = null;
  718. obj.computeWorldMatrix(true);
  719. }
  720. }
  721. }
  722. this._isDisposed = true;
  723. // Callback
  724. if (this.onDispose) {
  725. this.onDispose();
  726. }
  727. };
  728. // Physics
  729. BABYLON.Mesh.prototype.setPhysicsState = function (options) {
  730. if (!this._scene._physicsEngine) {
  731. return;
  732. }
  733. options.impostor = options.impostor || BABYLON.PhysicsEngine.NoImpostor;
  734. options.mass = options.mass || 0;
  735. options.friction = options.friction || 0.2;
  736. options.restitution = options.restitution || 0.9;
  737. this._physicImpostor = options.impostor;
  738. this._physicsMass = options.mass;
  739. this._physicsFriction = options.friction;
  740. this._physicRestitution = options.restitution;
  741. if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
  742. this._scene._physicsEngine._unregisterMesh(this);
  743. return;
  744. }
  745. this._scene._physicsEngine._registerMesh(this, options);
  746. };
  747. BABYLON.Mesh.prototype.getPhysicsImpostor = function () {
  748. if (!this._physicImpostor) {
  749. return BABYLON.PhysicsEngine.NoImpostor;
  750. }
  751. return this._physicImpostor;
  752. };
  753. BABYLON.Mesh.prototype.getPhysicsMass = function () {
  754. if (!this._physicsMass) {
  755. return 0;
  756. }
  757. return this._physicsMass;
  758. };
  759. BABYLON.Mesh.prototype.getPhysicsFriction = function () {
  760. if (!this._physicsFriction) {
  761. return 0;
  762. }
  763. return this._physicsFriction;
  764. };
  765. BABYLON.Mesh.prototype.getPhysicsRestitution = function () {
  766. if (!this._physicRestitution) {
  767. return 0;
  768. }
  769. return this._physicRestitution;
  770. };
  771. BABYLON.Mesh.prototype.applyImpulse = function (force, contactPoint) {
  772. if (!this._physicImpostor) {
  773. return;
  774. }
  775. this._scene._physicsEngine._applyImpulse(this, force, contactPoint);
  776. };
  777. BABYLON.Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
  778. if (!this._physicImpostor) {
  779. return;
  780. }
  781. this._scene._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
  782. };
  783. // Geometric tools
  784. BABYLON.Mesh.prototype.convertToFlatShadedMesh = function() {
  785. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  786. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  787. var kinds = this.getVerticesDataKinds();
  788. var vbs = [];
  789. var data = [];
  790. var newdata = [];
  791. var updatableNormals = false;
  792. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  793. var kind = kinds[kindIndex];
  794. if (kind === BABYLON.VertexBuffer.NormalKind) {
  795. updatableNormals = this.getVertexBuffer(kind).isUpdatable();
  796. kinds.splice(kindIndex, 1);
  797. kindIndex--;
  798. continue;
  799. }
  800. vbs[kind] = this.getVertexBuffer(kind);
  801. data[kind] = vbs[kind].getData();
  802. newdata[kind] = [];
  803. }
  804. // Save previous submeshes
  805. var previousSubmeshes = this.subMeshes.slice(0);
  806. var indices = this.getIndices();
  807. // Generating unique vertices per face
  808. for (var index = 0; index < indices.length; index++) {
  809. var vertexIndex = indices[index];
  810. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  811. var kind = kinds[kindIndex];
  812. var stride = vbs[kind].getStrideSize();
  813. for (var offset = 0; offset < stride; offset++) {
  814. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  815. }
  816. }
  817. }
  818. // Updating faces & normal
  819. var normals = [];
  820. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  821. for (var index = 0; index < indices.length; index += 3) {
  822. indices[index] = index;
  823. indices[index + 1] = index + 1;
  824. indices[index + 2] = index + 2;
  825. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  826. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  827. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  828. var p1p2 = p1.subtract(p2);
  829. var p3p2 = p3.subtract(p2);
  830. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  831. // Store same normals for every vertex
  832. for (var localIndex = 0; localIndex < 3; localIndex++) {
  833. normals.push(normal.x);
  834. normals.push(normal.y);
  835. normals.push(normal.z);
  836. }
  837. }
  838. this.setIndices(indices);
  839. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  840. // Updating vertex buffers
  841. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  842. var kind = kinds[kindIndex];
  843. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  844. }
  845. // Updating submeshes
  846. this.subMeshes = [];
  847. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  848. var previousOne = previousSubmeshes[submeshIndex];
  849. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  850. }
  851. };
  852. // Statics
  853. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  854. var box = new BABYLON.Mesh(name, scene);
  855. var normalsSource = [
  856. new BABYLON.Vector3(0, 0, 1),
  857. new BABYLON.Vector3(0, 0, -1),
  858. new BABYLON.Vector3(1, 0, 0),
  859. new BABYLON.Vector3(-1, 0, 0),
  860. new BABYLON.Vector3(0, 1, 0),
  861. new BABYLON.Vector3(0, -1, 0)
  862. ];
  863. var indices = [];
  864. var positions = [];
  865. var normals = [];
  866. var uvs = [];
  867. // Create each face in turn.
  868. for (var index = 0; index < normalsSource.length; index++) {
  869. var normal = normalsSource[index];
  870. // Get two vectors perpendicular to the face normal and to each other.
  871. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  872. var side2 = BABYLON.Vector3.Cross(normal, side1);
  873. // Six indices (two triangles) per face.
  874. var verticesLength = positions.length / 3;
  875. indices.push(verticesLength);
  876. indices.push(verticesLength + 1);
  877. indices.push(verticesLength + 2);
  878. indices.push(verticesLength);
  879. indices.push(verticesLength + 2);
  880. indices.push(verticesLength + 3);
  881. // Four vertices per face.
  882. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  883. positions.push(vertex.x, vertex.y, vertex.z);
  884. normals.push(normal.x, normal.y, normal.z);
  885. uvs.push(1.0, 1.0);
  886. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  887. positions.push(vertex.x, vertex.y, vertex.z);
  888. normals.push(normal.x, normal.y, normal.z);
  889. uvs.push(0.0, 1.0);
  890. vertex = normal.add(side1).add(side2).scale(size / 2);
  891. positions.push(vertex.x, vertex.y, vertex.z);
  892. normals.push(normal.x, normal.y, normal.z);
  893. uvs.push(0.0, 0.0);
  894. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  895. positions.push(vertex.x, vertex.y, vertex.z);
  896. normals.push(normal.x, normal.y, normal.z);
  897. uvs.push(1.0, 0.0);
  898. }
  899. box.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  900. box.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  901. box.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  902. box.setIndices(indices);
  903. return box;
  904. };
  905. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  906. var sphere = new BABYLON.Mesh(name, scene);
  907. var radius = diameter / 2;
  908. var totalZRotationSteps = 2 + segments;
  909. var totalYRotationSteps = 2 * totalZRotationSteps;
  910. var indices = [];
  911. var positions = [];
  912. var normals = [];
  913. var uvs = [];
  914. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  915. var normalizedZ = zRotationStep / totalZRotationSteps;
  916. var angleZ = (normalizedZ * Math.PI);
  917. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  918. var normalizedY = yRotationStep / totalYRotationSteps;
  919. var angleY = normalizedY * Math.PI * 2;
  920. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  921. var rotationY = BABYLON.Matrix.RotationY(angleY);
  922. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  923. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  924. var vertex = complete.scale(radius);
  925. var normal = BABYLON.Vector3.Normalize(vertex);
  926. positions.push(vertex.x, vertex.y, vertex.z);
  927. normals.push(normal.x, normal.y, normal.z);
  928. uvs.push(normalizedZ, normalizedY);
  929. }
  930. if (zRotationStep > 0) {
  931. var verticesCount = positions.length / 3;
  932. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  933. indices.push((firstIndex));
  934. indices.push((firstIndex + 1));
  935. indices.push(firstIndex + totalYRotationSteps + 1);
  936. indices.push((firstIndex + totalYRotationSteps + 1));
  937. indices.push((firstIndex + 1));
  938. indices.push((firstIndex + totalYRotationSteps + 2));
  939. }
  940. }
  941. }
  942. sphere.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  943. sphere.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  944. sphere.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  945. sphere.setIndices(indices);
  946. return sphere;
  947. };
  948. // Cylinder and cone (Code inspired by SharpDX.org)
  949. BABYLON.Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
  950. var radiusTop = diameterTop / 2;
  951. var radiusBottom = diameterBottom / 2;
  952. var indices = [];
  953. var positions = [];
  954. var normals = [];
  955. var uvs = [];
  956. var cylinder = new BABYLON.Mesh(name, scene);
  957. var getCircleVector = function (i) {
  958. var angle = (i * 2.0 * Math.PI / tessellation);
  959. var dx = Math.sin(angle);
  960. var dz = Math.cos(angle);
  961. return new BABYLON.Vector3(dx, 0, dz);
  962. };
  963. var createCylinderCap = function (isTop) {
  964. var radius = isTop ? radiusTop : radiusBottom;
  965. if (radius == 0) {
  966. return
  967. }
  968. // Create cap indices.
  969. for (var i = 0; i < tessellation - 2; i++) {
  970. var i1 = (i + 1) % tessellation;
  971. var i2 = (i + 2) % tessellation;
  972. if (!isTop) {
  973. var tmp = i1;
  974. var i1 = i2;
  975. i2 = tmp;
  976. }
  977. var vbase = positions.length / 3;
  978. indices.push(vbase);
  979. indices.push(vbase + i1);
  980. indices.push(vbase + i2);
  981. }
  982. // Which end of the cylinder is this?
  983. var normal = new BABYLON.Vector3(0, -1, 0);
  984. var textureScale = new BABYLON.Vector2(-0.5, -0.5);
  985. if (!isTop) {
  986. normal = normal.scale(-1);
  987. textureScale.x = -textureScale.x;
  988. }
  989. // Create cap vertices.
  990. for (var i = 0; i < tessellation; i++) {
  991. var circleVector = getCircleVector(i);
  992. var position = circleVector.scale(radius).add(normal.scale(height));
  993. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  994. positions.push(position.x, position.y, position.z);
  995. normals.push(normal.x, normal.y, normal.z);
  996. uvs.push(textureCoordinate.x, textureCoordinate.y);
  997. }
  998. };
  999. height /= 2;
  1000. var topOffset = new BABYLON.Vector3(0, 1, 0).scale(height);
  1001. var stride = tessellation + 1;
  1002. // Create a ring of triangles around the outside of the cylinder.
  1003. for (var i = 0; i <= tessellation; i++) {
  1004. var normal = getCircleVector(i);
  1005. var sideOffsetBottom = normal.scale(radiusBottom);
  1006. var sideOffsetTop = normal.scale(radiusTop);
  1007. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  1008. var position = sideOffsetBottom.add(topOffset);
  1009. positions.push(position.x, position.y, position.z);
  1010. normals.push(normal.x, normal.y, normal.z);
  1011. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1012. position = sideOffsetTop.subtract(topOffset);
  1013. textureCoordinate.y += 1;
  1014. positions.push(position.x, position.y, position.z);
  1015. normals.push(normal.x, normal.y, normal.z);
  1016. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1017. indices.push(i * 2);
  1018. indices.push((i * 2 + 2) % (stride * 2));
  1019. indices.push(i * 2 + 1);
  1020. indices.push(i * 2 + 1);
  1021. indices.push((i * 2 + 2) % (stride * 2));
  1022. indices.push((i * 2 + 3) % (stride * 2));
  1023. }
  1024. // Create flat triangle fan caps to seal the top and bottom.
  1025. createCylinderCap(true);
  1026. createCylinderCap(false);
  1027. cylinder.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1028. cylinder.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1029. cylinder.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1030. cylinder.setIndices(indices);
  1031. return cylinder;
  1032. };
  1033. // Torus (Code from SharpDX.org)
  1034. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  1035. var torus = new BABYLON.Mesh(name, scene);
  1036. var indices = [];
  1037. var positions = [];
  1038. var normals = [];
  1039. var uvs = [];
  1040. var stride = tessellation + 1;
  1041. for (var i = 0; i <= tessellation; i++) {
  1042. var u = i / tessellation;
  1043. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  1044. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  1045. for (var j = 0; j <= tessellation; j++) {
  1046. var v = 1 - j / tessellation;
  1047. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  1048. var dx = Math.cos(innerAngle);
  1049. var dy = Math.sin(innerAngle);
  1050. // Create a vertex.
  1051. var normal = new BABYLON.Vector3(dx, dy, 0);
  1052. var position = normal.scale(thickness / 2);
  1053. var textureCoordinate = new BABYLON.Vector2(u, v);
  1054. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  1055. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  1056. positions.push(position.x, position.y, position.z);
  1057. normals.push(normal.x, normal.y, normal.z);
  1058. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1059. // And create indices for two triangles.
  1060. var nextI = (i + 1) % stride;
  1061. var nextJ = (j + 1) % stride;
  1062. indices.push(i * stride + j);
  1063. indices.push(i * stride + nextJ);
  1064. indices.push(nextI * stride + j);
  1065. indices.push(i * stride + nextJ);
  1066. indices.push(nextI * stride + nextJ);
  1067. indices.push(nextI * stride + j);
  1068. }
  1069. }
  1070. torus.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1071. torus.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1072. torus.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1073. torus.setIndices(indices);
  1074. return torus;
  1075. };
  1076. // Plane
  1077. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  1078. var plane = new BABYLON.Mesh(name, scene);
  1079. var indices = [];
  1080. var positions = [];
  1081. var normals = [];
  1082. var uvs = [];
  1083. // Vertices
  1084. var halfSize = size / 2.0;
  1085. positions.push(-halfSize, -halfSize, 0);
  1086. normals.push(0, 0, -1.0);
  1087. uvs.push(0.0, 0.0);
  1088. positions.push(halfSize, -halfSize, 0);
  1089. normals.push(0, 0, -1.0);
  1090. uvs.push(1.0, 0.0);
  1091. positions.push(halfSize, halfSize, 0);
  1092. normals.push(0, 0, -1.0);
  1093. uvs.push(1.0, 1.0);
  1094. positions.push(-halfSize, halfSize, 0);
  1095. normals.push(0, 0, -1.0);
  1096. uvs.push(0.0, 1.0);
  1097. // Indices
  1098. indices.push(0);
  1099. indices.push(1);
  1100. indices.push(2);
  1101. indices.push(0);
  1102. indices.push(2);
  1103. indices.push(3);
  1104. plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1105. plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1106. plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1107. plane.setIndices(indices);
  1108. return plane;
  1109. };
  1110. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  1111. var ground = new BABYLON.Mesh(name, scene);
  1112. var indices = [];
  1113. var positions = [];
  1114. var normals = [];
  1115. var uvs = [];
  1116. var row, col;
  1117. for (row = 0; row <= subdivisions; row++) {
  1118. for (col = 0; col <= subdivisions; col++) {
  1119. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1120. var normal = new BABYLON.Vector3(0, 1.0, 0);
  1121. positions.push(position.x, position.y, position.z);
  1122. normals.push(normal.x, normal.y, normal.z);
  1123. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1124. }
  1125. }
  1126. for (row = 0; row < subdivisions; row++) {
  1127. for (col = 0; col < subdivisions; col++) {
  1128. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1129. indices.push(col + 1 + row * (subdivisions + 1));
  1130. indices.push(col + row * (subdivisions + 1));
  1131. indices.push(col + (row + 1) * (subdivisions + 1));
  1132. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1133. indices.push(col + row * (subdivisions + 1));
  1134. }
  1135. }
  1136. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1137. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1138. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1139. ground.setIndices(indices);
  1140. return ground;
  1141. };
  1142. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  1143. var ground = new BABYLON.Mesh(name, scene);
  1144. var onload = function (img) {
  1145. var indices = [];
  1146. var positions = [];
  1147. var normals = [];
  1148. var uvs = [];
  1149. var row, col;
  1150. // Getting height map data
  1151. var canvas = document.createElement("canvas");
  1152. var context = canvas.getContext("2d");
  1153. var heightMapWidth = img.width;
  1154. var heightMapHeight = img.height;
  1155. canvas.width = heightMapWidth;
  1156. canvas.height = heightMapHeight;
  1157. context.drawImage(img, 0, 0);
  1158. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1159. // Vertices
  1160. for (row = 0; row <= subdivisions; row++) {
  1161. for (col = 0; col <= subdivisions; col++) {
  1162. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1163. // Compute height
  1164. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  1165. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  1166. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  1167. var r = buffer[pos] / 255.0;
  1168. var g = buffer[pos + 1] / 255.0;
  1169. var b = buffer[pos + 2] / 255.0;
  1170. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1171. position.y = minHeight + (maxHeight - minHeight) * gradient;
  1172. // Add vertex
  1173. positions.push(position.x, position.y, position.z);
  1174. normals.push(0, 0, 0);
  1175. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1176. }
  1177. }
  1178. // Indices
  1179. for (row = 0; row < subdivisions; row++) {
  1180. for (col = 0; col < subdivisions; col++) {
  1181. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1182. indices.push(col + 1 + row * (subdivisions + 1));
  1183. indices.push(col + row * (subdivisions + 1));
  1184. indices.push(col + (row + 1) * (subdivisions + 1));
  1185. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1186. indices.push(col + row * (subdivisions + 1));
  1187. }
  1188. }
  1189. // Normals
  1190. BABYLON.Mesh.ComputeNormal(positions, normals, indices);
  1191. // Transfer
  1192. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1193. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1194. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1195. ground.setIndices(indices);
  1196. ground._isReady = true;
  1197. };
  1198. BABYLON.Tools.LoadImage(url, onload, scene.database);
  1199. ground._isReady = false;
  1200. return ground;
  1201. };
  1202. // Tools
  1203. BABYLON.Mesh.ComputeNormal = function (positions, normals, indices) {
  1204. var positionVectors = [];
  1205. var facesOfVertices = [];
  1206. var index;
  1207. for (index = 0; index < positions.length; index += 3) {
  1208. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  1209. positionVectors.push(vector3);
  1210. facesOfVertices.push([]);
  1211. }
  1212. // Compute normals
  1213. var facesNormals = [];
  1214. for (index = 0; index < indices.length / 3; index++) {
  1215. var i1 = indices[index * 3];
  1216. var i2 = indices[index * 3 + 1];
  1217. var i3 = indices[index * 3 + 2];
  1218. var p1 = positionVectors[i1];
  1219. var p2 = positionVectors[i2];
  1220. var p3 = positionVectors[i3];
  1221. var p1p2 = p1.subtract(p2);
  1222. var p3p2 = p3.subtract(p2);
  1223. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  1224. facesOfVertices[i1].push(index);
  1225. facesOfVertices[i2].push(index);
  1226. facesOfVertices[i3].push(index);
  1227. }
  1228. for (index = 0; index < positionVectors.length; index++) {
  1229. var faces = facesOfVertices[index];
  1230. var normal = BABYLON.Vector3.Zero();
  1231. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  1232. normal.addInPlace(facesNormals[faces[faceIndex]]);
  1233. }
  1234. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  1235. normals[index * 3] = normal.x;
  1236. normals[index * 3 + 1] = normal.y;
  1237. normals[index * 3 + 2] = normal.z;
  1238. }
  1239. };
  1240. })();