babylon.mesh.js 50 KB

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