babylon.mesh.js 46 KB

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