babylon.mesh.js 57 KB

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