babylon.mesh.js 45 KB

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