babylon.mesh.js 58 KB

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