babylon.mesh.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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._currentRenderId == this._scene.getRenderId() || 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. this._resetPointsArrayCache();
  349. var stride = this._vertexBuffers[kind].getStrideSize();
  350. this._totalVertices = data.length / stride;
  351. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  352. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  353. this._createGlobalSubMesh();
  354. }
  355. };
  356. BABYLON.Mesh.prototype.updateVerticesData = function (kind, data, updateExtends) {
  357. if (this._vertexBuffers[kind]) {
  358. this._vertexBuffers[kind].update(data);
  359. if (kind === BABYLON.VertexBuffer.PositionKind) {
  360. this._resetPointsArrayCache();
  361. if (updateExtends) {
  362. var stride = this._vertexBuffers[kind].getStrideSize();
  363. this._totalVertices = data.length / stride;
  364. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  365. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  366. }
  367. }
  368. }
  369. };
  370. BABYLON.Mesh.prototype.setIndices = function (indices) {
  371. if (this._indexBuffer) {
  372. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  373. }
  374. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  375. this._indices = indices;
  376. this._createGlobalSubMesh();
  377. };
  378. BABYLON.Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  379. var engine = this._scene.getEngine();
  380. // Wireframe
  381. var indexToBind = this._indexBuffer;
  382. var useTriangles = true;
  383. if (wireframe) {
  384. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  385. useTriangles = false;
  386. }
  387. // VBOs
  388. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  389. // Draw order
  390. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  391. };
  392. BABYLON.Mesh.prototype.registerBeforeRender = function (func) {
  393. this._onBeforeRenderCallbacks.push(func);
  394. };
  395. BABYLON.Mesh.prototype.unregisterBeforeRender = function (func) {
  396. var index = this._onBeforeRenderCallbacks.indexOf(func);
  397. if (index > -1) {
  398. this._onBeforeRenderCallbacks.splice(index, 1);
  399. }
  400. };
  401. BABYLON.Mesh.prototype.render = function (subMesh) {
  402. if (!this._vertexBuffers || !this._indexBuffer) {
  403. return;
  404. }
  405. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  406. this._onBeforeRenderCallbacks[callbackIndex]();
  407. }
  408. // World
  409. var world = this.getWorldMatrix();
  410. // Material
  411. var effectiveMaterial = subMesh.getMaterial();
  412. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  413. return;
  414. }
  415. effectiveMaterial._preBind();
  416. effectiveMaterial.bind(world, this);
  417. // Bind and draw
  418. var engine = this._scene.getEngine();
  419. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  420. // Unbind
  421. effectiveMaterial.unbind();
  422. };
  423. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  424. var results = [];
  425. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  426. var particleSystem = this._scene.particleSystems[index];
  427. if (particleSystem.emitter === this) {
  428. results.push(particleSystem);
  429. }
  430. }
  431. return results;
  432. };
  433. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  434. var results = [];
  435. var descendants = this.getDescendants();
  436. descendants.push(this);
  437. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  438. var particleSystem = this._scene.particleSystems[index];
  439. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  440. results.push(particleSystem);
  441. }
  442. }
  443. return results;
  444. };
  445. BABYLON.Mesh.prototype.getChildren = function () {
  446. var results = [];
  447. for (var index = 0; index < this._scene.meshes.length; index++) {
  448. var mesh = this._scene.meshes[index];
  449. if (mesh.parent == this) {
  450. results.push(mesh);
  451. }
  452. }
  453. return results;
  454. };
  455. BABYLON.Mesh.prototype.isInFrustum = function (frustumPlanes) {
  456. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  457. return false;
  458. }
  459. var result = this._boundingInfo.isInFrustum(frustumPlanes);
  460. if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  461. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  462. var that = this;
  463. this._scene._addPendingData(this);
  464. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  465. that._delayLoadingFunction(JSON.parse(data), that);
  466. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  467. that._scene._removePendingData(that);
  468. }, function () { }, this._scene.database);
  469. }
  470. return result;
  471. };
  472. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  473. var materials = this._scene.materials;
  474. for (var index = 0; index < materials.length; index++) {
  475. if (materials[index].id == id) {
  476. this.material = materials[index];
  477. return;
  478. }
  479. }
  480. // Multi
  481. var multiMaterials = this._scene.multiMaterials;
  482. for (var index = 0; index < multiMaterials.length; index++) {
  483. if (multiMaterials[index].id == id) {
  484. this.material = multiMaterials[index];
  485. return;
  486. }
  487. }
  488. };
  489. BABYLON.Mesh.prototype.getAnimatables = function () {
  490. var results = [];
  491. if (this.material) {
  492. results.push(this.material);
  493. }
  494. return results;
  495. };
  496. // Geometry
  497. BABYLON.Mesh.prototype.setPositionWithLocalVector = function (vector3) {
  498. this.computeWorldMatrix();
  499. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  500. };
  501. BABYLON.Mesh.prototype.getPositionExpressedInLocalSpace = function () {
  502. this.computeWorldMatrix();
  503. var invLocalWorldMatrix = this._localWorld.clone();
  504. invLocalWorldMatrix.invert();
  505. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  506. };
  507. BABYLON.Mesh.prototype.locallyTranslate = function (vector3) {
  508. this.computeWorldMatrix();
  509. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  510. };
  511. BABYLON.Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  512. // Position
  513. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  514. return;
  515. }
  516. this._resetPointsArrayCache();
  517. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  518. var temp = new BABYLON.MatrixType(data.length);
  519. for (var index = 0; index < data.length; index += 3) {
  520. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  521. }
  522. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].isUpdatable());
  523. // Normals
  524. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  525. return;
  526. }
  527. data = this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].getData();
  528. for (var index = 0; index < data.length; index += 3) {
  529. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  530. }
  531. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].isUpdatable());
  532. };
  533. BABYLON.Mesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  534. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  535. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  536. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  537. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  538. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  539. /// <returns>Mesh oriented towards targetMesh</returns>
  540. yawCor = yawCor || 0; // default to zero if undefined
  541. pitchCor = pitchCor || 0;
  542. rollCor = rollCor || 0;
  543. var dv = targetPoint.subtract(this.position);
  544. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  545. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  546. var pitch = Math.atan2(dv.y, len);
  547. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  548. };
  549. // Cache
  550. BABYLON.Mesh.prototype._resetPointsArrayCache = function () {
  551. this._positions = null;
  552. };
  553. BABYLON.Mesh.prototype._generatePointsArray = function () {
  554. if (this._positions)
  555. return;
  556. this._positions = [];
  557. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  558. for (var index = 0; index < data.length; index += 3) {
  559. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  560. }
  561. };
  562. // Collisions
  563. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  564. this._generatePointsArray();
  565. // Transformation
  566. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  567. subMesh._lastColliderTransformMatrix = transformMatrix;
  568. subMesh._lastColliderWorldVertices = [];
  569. var start = subMesh.verticesStart;
  570. var end = (subMesh.verticesStart + subMesh.verticesCount);
  571. for (var i = start; i < end; i++) {
  572. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  573. }
  574. }
  575. // Collide
  576. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  577. };
  578. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  579. for (var index = 0; index < this.subMeshes.length; index++) {
  580. var subMesh = this.subMeshes[index];
  581. // Bounding test
  582. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  583. continue;
  584. this._collideForSubMesh(subMesh, transformMatrix, collider);
  585. }
  586. };
  587. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  588. // Bounding box test
  589. if (!this._boundingInfo._checkCollision(collider))
  590. return;
  591. // Transformation matrix
  592. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  593. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  594. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  595. };
  596. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  597. if (!this._boundingInfo || !mesh._boundingInfo) {
  598. return false;
  599. }
  600. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  601. };
  602. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  603. if (!this._boundingInfo) {
  604. return false;
  605. }
  606. return this._boundingInfo.intersectsPoint(point);
  607. };
  608. // Picking
  609. BABYLON.Mesh.prototype.intersects = function (ray, fastCheck) {
  610. var pickingInfo = new BABYLON.PickingInfo();
  611. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  612. return pickingInfo;
  613. }
  614. this._generatePointsArray();
  615. var intersectInfo = null;
  616. for (var index = 0; index < this.subMeshes.length; index++) {
  617. var subMesh = this.subMeshes[index];
  618. // Bounding test
  619. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  620. continue;
  621. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  622. if (currentIntersectInfo) {
  623. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  624. intersectInfo = currentIntersectInfo;
  625. if (fastCheck) {
  626. break;
  627. }
  628. }
  629. }
  630. }
  631. if (intersectInfo) {
  632. // Get picked point
  633. var world = this.getWorldMatrix();
  634. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  635. var direction = ray.direction.clone();
  636. direction.normalize();
  637. direction = direction.scale(intersectInfo.distance);
  638. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  639. var pickedPoint = worldOrigin.add(worldDirection);
  640. // Return result
  641. pickingInfo.hit = true;
  642. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  643. pickingInfo.pickedPoint = pickedPoint;
  644. pickingInfo.pickedMesh = this;
  645. pickingInfo.bu = intersectInfo.bu;
  646. pickingInfo.bv = intersectInfo.bv;
  647. pickingInfo.faceId = intersectInfo.faceId;
  648. return pickingInfo;
  649. }
  650. return pickingInfo;
  651. };
  652. // Clone
  653. BABYLON.Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  654. var result = new BABYLON.Mesh(name, this._scene);
  655. // Buffers
  656. result._vertexBuffers = this._vertexBuffers;
  657. for (var kind in result._vertexBuffers) {
  658. result._vertexBuffers[kind]._buffer.references++;
  659. }
  660. result._indexBuffer = this._indexBuffer;
  661. this._indexBuffer.references++;
  662. // Deep copy
  663. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  664. // Bounding info
  665. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  666. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  667. // Material
  668. result.material = this.material;
  669. // Parent
  670. if (newParent) {
  671. result.parent = newParent;
  672. }
  673. if (!doNotCloneChildren) {
  674. // Children
  675. for (var index = 0; index < this._scene.meshes.length; index++) {
  676. var mesh = this._scene.meshes[index];
  677. if (mesh.parent == this) {
  678. mesh.clone(mesh.name, result);
  679. }
  680. }
  681. }
  682. // Particles
  683. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  684. var system = this._scene.particleSystems[index];
  685. if (system.emitter == this) {
  686. system.clone(system.name, result);
  687. }
  688. }
  689. result.computeWorldMatrix(true);
  690. return result;
  691. };
  692. // Dispose
  693. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  694. if (this._vertexBuffers) {
  695. for (var vbKind in this._vertexBuffers) {
  696. this._vertexBuffers[vbKind].dispose();
  697. }
  698. this._vertexBuffers = null;
  699. }
  700. if (this._indexBuffer) {
  701. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  702. this._indexBuffer = null;
  703. }
  704. // Physics
  705. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  706. this.setPhysicsState({ impostor: BABYLON.PhysicsEngine.NoImpostor });
  707. }
  708. // Remove from scene
  709. var index = this._scene.meshes.indexOf(this);
  710. this._scene.meshes.splice(index, 1);
  711. if (!doNotRecurse) {
  712. // Particles
  713. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  714. if (this._scene.particleSystems[index].emitter == this) {
  715. this._scene.particleSystems[index].dispose();
  716. index--;
  717. }
  718. }
  719. // Children
  720. var objects = this._scene.meshes.slice(0);
  721. for (var index = 0; index < objects.length; index++) {
  722. if (objects[index].parent == this) {
  723. objects[index].dispose();
  724. }
  725. }
  726. } else {
  727. for (var index = 0; index < this._scene.meshes.length; index++) {
  728. var obj = this._scene.meshes[index];
  729. if (obj.parent === this) {
  730. obj.parent = null;
  731. obj.computeWorldMatrix(true);
  732. }
  733. }
  734. }
  735. this._isDisposed = true;
  736. // Callback
  737. if (this.onDispose) {
  738. this.onDispose();
  739. }
  740. };
  741. // Physics
  742. BABYLON.Mesh.prototype.setPhysicsState = function (options) {
  743. if (!this._scene._physicsEngine) {
  744. return;
  745. }
  746. options.impostor = options.impostor || BABYLON.PhysicsEngine.NoImpostor;
  747. options.mass = options.mass || 0;
  748. options.friction = options.friction || 0.2;
  749. options.restitution = options.restitution || 0.9;
  750. this._physicImpostor = options.impostor;
  751. this._physicsMass = options.mass;
  752. this._physicsFriction = options.friction;
  753. this._physicRestitution = options.restitution;
  754. if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
  755. this._scene._physicsEngine._unregisterMesh(this);
  756. return;
  757. }
  758. this._scene._physicsEngine._registerMesh(this, options);
  759. };
  760. BABYLON.Mesh.prototype.getPhysicsImpostor = function () {
  761. if (!this._physicImpostor) {
  762. return BABYLON.PhysicsEngine.NoImpostor;
  763. }
  764. return this._physicImpostor;
  765. };
  766. BABYLON.Mesh.prototype.getPhysicsMass = function () {
  767. if (!this._physicsMass) {
  768. return 0;
  769. }
  770. return this._physicsMass;
  771. };
  772. BABYLON.Mesh.prototype.getPhysicsFriction = function () {
  773. if (!this._physicsFriction) {
  774. return 0;
  775. }
  776. return this._physicsFriction;
  777. };
  778. BABYLON.Mesh.prototype.getPhysicsRestitution = function () {
  779. if (!this._physicRestitution) {
  780. return 0;
  781. }
  782. return this._physicRestitution;
  783. };
  784. BABYLON.Mesh.prototype.applyImpulse = function (force, contactPoint) {
  785. if (!this._physicImpostor) {
  786. return;
  787. }
  788. this._scene._physicsEngine._applyImpulse(this, force, contactPoint);
  789. };
  790. BABYLON.Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
  791. if (!this._physicImpostor) {
  792. return;
  793. }
  794. this._scene._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
  795. };
  796. // Geometric tools
  797. BABYLON.Mesh.prototype.convertToFlatShadedMesh = function () {
  798. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  799. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  800. var kinds = this.getVerticesDataKinds();
  801. var vbs = [];
  802. var data = [];
  803. var newdata = [];
  804. var updatableNormals = false;
  805. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  806. var kind = kinds[kindIndex];
  807. if (kind === BABYLON.VertexBuffer.NormalKind) {
  808. updatableNormals = this.getVertexBuffer(kind).isUpdatable();
  809. kinds.splice(kindIndex, 1);
  810. kindIndex--;
  811. continue;
  812. }
  813. vbs[kind] = this.getVertexBuffer(kind);
  814. data[kind] = vbs[kind].getData();
  815. newdata[kind] = [];
  816. }
  817. // Save previous submeshes
  818. var previousSubmeshes = this.subMeshes.slice(0);
  819. var indices = this.getIndices();
  820. // Generating unique vertices per face
  821. for (var index = 0; index < indices.length; index++) {
  822. var vertexIndex = indices[index];
  823. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  824. var kind = kinds[kindIndex];
  825. var stride = vbs[kind].getStrideSize();
  826. for (var offset = 0; offset < stride; offset++) {
  827. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  828. }
  829. }
  830. }
  831. // Updating faces & normal
  832. var normals = [];
  833. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  834. for (var index = 0; index < indices.length; index += 3) {
  835. indices[index] = index;
  836. indices[index + 1] = index + 1;
  837. indices[index + 2] = index + 2;
  838. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  839. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  840. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  841. var p1p2 = p1.subtract(p2);
  842. var p3p2 = p3.subtract(p2);
  843. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  844. // Store same normals for every vertex
  845. for (var localIndex = 0; localIndex < 3; localIndex++) {
  846. normals.push(normal.x);
  847. normals.push(normal.y);
  848. normals.push(normal.z);
  849. }
  850. }
  851. this.setIndices(indices);
  852. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  853. // Updating vertex buffers
  854. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  855. var kind = kinds[kindIndex];
  856. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  857. }
  858. // Updating submeshes
  859. this.subMeshes = [];
  860. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  861. var previousOne = previousSubmeshes[submeshIndex];
  862. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  863. }
  864. };
  865. // Statics
  866. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  867. var box = new BABYLON.Mesh(name, scene);
  868. var vertexData = BABYLON.VertexData.CreateBox(size);
  869. vertexData.applyToMesh(box, updatable);
  870. return box;
  871. };
  872. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  873. var sphere = new BABYLON.Mesh(name, scene);
  874. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  875. vertexData.applyToMesh(sphere, updatable);
  876. return sphere;
  877. };
  878. // Cylinder and cone (Code inspired by SharpDX.org)
  879. BABYLON.Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
  880. var cylinder = new BABYLON.Mesh(name, scene);
  881. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  882. vertexData.applyToMesh(cylinder, updatable);
  883. return cylinder;
  884. };
  885. // Torus (Code from SharpDX.org)
  886. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  887. var torus = new BABYLON.Mesh(name, scene);
  888. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  889. vertexData.applyToMesh(torus, updatable);
  890. return torus;
  891. };
  892. // Plane & ground
  893. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  894. var plane = new BABYLON.Mesh(name, scene);
  895. var vertexData = BABYLON.VertexData.CreatePlane(size);
  896. vertexData.applyToMesh(plane, updatable);
  897. return plane;
  898. };
  899. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  900. var ground = new BABYLON.Mesh(name, scene);
  901. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  902. vertexData.applyToMesh(ground, updatable);
  903. return ground;
  904. };
  905. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  906. var ground = new BABYLON.Mesh(name, scene);
  907. var onload = function (img) {
  908. var indices = [];
  909. var positions = [];
  910. var normals = [];
  911. var uvs = [];
  912. var row, col;
  913. // Getting height map data
  914. var canvas = document.createElement("canvas");
  915. var context = canvas.getContext("2d");
  916. var heightMapWidth = img.width;
  917. var heightMapHeight = img.height;
  918. canvas.width = heightMapWidth;
  919. canvas.height = heightMapHeight;
  920. context.drawImage(img, 0, 0);
  921. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  922. // Vertices
  923. for (row = 0; row <= subdivisions; row++) {
  924. for (col = 0; col <= subdivisions; col++) {
  925. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  926. // Compute height
  927. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  928. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  929. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  930. var r = buffer[pos] / 255.0;
  931. var g = buffer[pos + 1] / 255.0;
  932. var b = buffer[pos + 2] / 255.0;
  933. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  934. position.y = minHeight + (maxHeight - minHeight) * gradient;
  935. // Add vertex
  936. positions.push(position.x, position.y, position.z);
  937. normals.push(0, 0, 0);
  938. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  939. }
  940. }
  941. // Indices
  942. for (row = 0; row < subdivisions; row++) {
  943. for (col = 0; col < subdivisions; col++) {
  944. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  945. indices.push(col + 1 + row * (subdivisions + 1));
  946. indices.push(col + row * (subdivisions + 1));
  947. indices.push(col + (row + 1) * (subdivisions + 1));
  948. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  949. indices.push(col + row * (subdivisions + 1));
  950. }
  951. }
  952. // Normals
  953. BABYLON.Mesh.ComputeNormal(positions, normals, indices);
  954. // Transfer
  955. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  956. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  957. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  958. ground.setIndices(indices);
  959. ground._isReady = true;
  960. };
  961. BABYLON.Tools.LoadImage(url, onload, scene.database);
  962. ground._isReady = false;
  963. return ground;
  964. };
  965. // Tools
  966. BABYLON.Mesh.ComputeNormal = function (positions, normals, indices) {
  967. var positionVectors = [];
  968. var facesOfVertices = [];
  969. var index;
  970. for (index = 0; index < positions.length; index += 3) {
  971. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  972. positionVectors.push(vector3);
  973. facesOfVertices.push([]);
  974. }
  975. // Compute normals
  976. var facesNormals = [];
  977. for (index = 0; index < indices.length / 3; index++) {
  978. var i1 = indices[index * 3];
  979. var i2 = indices[index * 3 + 1];
  980. var i3 = indices[index * 3 + 2];
  981. var p1 = positionVectors[i1];
  982. var p2 = positionVectors[i2];
  983. var p3 = positionVectors[i3];
  984. var p1p2 = p1.subtract(p2);
  985. var p3p2 = p3.subtract(p2);
  986. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  987. facesOfVertices[i1].push(index);
  988. facesOfVertices[i2].push(index);
  989. facesOfVertices[i3].push(index);
  990. }
  991. for (index = 0; index < positionVectors.length; index++) {
  992. var faces = facesOfVertices[index];
  993. var normal = BABYLON.Vector3.Zero();
  994. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  995. normal.addInPlace(facesNormals[faces[faceIndex]]);
  996. }
  997. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  998. normals[index * 3] = normal.x;
  999. normals[index * 3 + 1] = normal.y;
  1000. normals[index * 3 + 2] = normal.z;
  1001. }
  1002. };
  1003. BABYLON.Mesh.MinMax = function (meshes) {
  1004. var minVector;
  1005. var maxVector;
  1006. for (var i in meshes) {
  1007. var mesh = meshes[i];
  1008. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1009. if (!minVector) {
  1010. minVector = boundingBox.minimumWorld;
  1011. maxVector = boundingBox.maximumWorld;
  1012. continue;
  1013. }
  1014. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1015. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1016. }
  1017. return {
  1018. min: minVector,
  1019. max: maxVector
  1020. };
  1021. };
  1022. BABYLON.Mesh.Center = function (meshesOrMinMaxVector) {
  1023. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  1024. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  1025. };
  1026. })();