babylon.mesh.js 57 KB

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