babylon.mesh.js 51 KB

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