babylon.mesh.js 59 KB

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