babylon.mesh.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Mesh = (function (_super) {
  10. __extends(Mesh, _super);
  11. function Mesh(name, scene) {
  12. _super.call(this, name, scene);
  13. // Members
  14. this.position = new BABYLON.Vector3(0, 0, 0);
  15. this.rotation = new BABYLON.Vector3(0, 0, 0);
  16. this.rotationQuaternion = null;
  17. this.scaling = new BABYLON.Vector3(1, 1, 1);
  18. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19. this.material = null;
  20. this.isVisible = true;
  21. this.isPickable = true;
  22. this.visibility = 1.0;
  23. this.billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  24. this.checkCollisions = false;
  25. this.receiveShadows = false;
  26. this._isDisposed = false;
  27. this.onDispose = null;
  28. this.skeleton = null;
  29. this.renderingGroupId = 0;
  30. this.infiniteDistance = false;
  31. this.showBoundingBox = false;
  32. // Cache
  33. this._positions = null;
  34. this._localScaling = BABYLON.Matrix.Zero();
  35. this._localRotation = BABYLON.Matrix.Zero();
  36. this._localTranslation = BABYLON.Matrix.Zero();
  37. this._localBillboard = BABYLON.Matrix.Zero();
  38. this._localPivotScaling = BABYLON.Matrix.Zero();
  39. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  40. this._localWorld = BABYLON.Matrix.Zero();
  41. this._worldMatrix = BABYLON.Matrix.Zero();
  42. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  43. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  44. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  45. this._absolutePosition = BABYLON.Vector3.Zero();
  46. this._isDirty = false;
  47. // Physics
  48. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  49. this._pivotMatrix = BABYLON.Matrix.Identity();
  50. this._renderId = 0;
  51. this._onBeforeRenderCallbacks = [];
  52. this._animationStarted = false;
  53. scene.meshes.push(this);
  54. }
  55. Mesh.prototype.getBoundingInfo = function () {
  56. return this._boundingInfo;
  57. };
  58. Mesh.prototype.getWorldMatrix = function () {
  59. if (this._currentRenderId !== this.getScene().getRenderId()) {
  60. this.computeWorldMatrix();
  61. }
  62. return this._worldMatrix;
  63. };
  64. Mesh.prototype.rotate = function (axis, amount, space) {
  65. if (!this.rotationQuaternion) {
  66. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  67. this.rotation = BABYLON.Vector3.Zero();
  68. }
  69. if (!space || space == 0 /* LOCAL */) {
  70. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  71. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  72. } else {
  73. if (this.parent) {
  74. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  75. invertParentWorldMatrix.invert();
  76. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  77. }
  78. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  79. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  80. }
  81. };
  82. Mesh.prototype.translate = function (axis, distance, space) {
  83. var displacementVector = axis.scale(distance);
  84. if (!space || space == 0 /* LOCAL */) {
  85. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  86. this.setPositionWithLocalVector(tempV3);
  87. } else {
  88. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  89. }
  90. };
  91. Mesh.prototype.getAbsolutePosition = function () {
  92. this.computeWorldMatrix();
  93. return this._absolutePosition;
  94. };
  95. Mesh.prototype.setAbsolutePosition = function (absolutePosition) {
  96. if (!absolutePosition) {
  97. return;
  98. }
  99. var absolutePositionX;
  100. var absolutePositionY;
  101. var absolutePositionZ;
  102. if (absolutePosition.x === undefined) {
  103. if (arguments.length < 3) {
  104. return;
  105. }
  106. absolutePositionX = arguments[0];
  107. absolutePositionY = arguments[1];
  108. absolutePositionZ = arguments[2];
  109. } else {
  110. absolutePositionX = absolutePosition.x;
  111. absolutePositionY = absolutePosition.y;
  112. absolutePositionZ = absolutePosition.z;
  113. }
  114. if (this.parent) {
  115. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  116. invertParentWorldMatrix.invert();
  117. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  118. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  119. } else {
  120. this.position.x = absolutePositionX;
  121. this.position.y = absolutePositionY;
  122. this.position.z = absolutePositionZ;
  123. }
  124. };
  125. Mesh.prototype.getTotalVertices = function () {
  126. if (!this._geometry) {
  127. return 0;
  128. }
  129. return this._geometry.getTotalVertices();
  130. };
  131. Mesh.prototype.getVerticesData = function (kind) {
  132. if (!this._geometry) {
  133. return null;
  134. }
  135. return this._geometry.getVerticesData(kind);
  136. };
  137. Mesh.prototype.getVertexBuffer = function (kind) {
  138. if (!this._geometry) {
  139. return undefined;
  140. }
  141. return this._geometry.getVertexBuffer(kind);
  142. };
  143. Mesh.prototype.isVerticesDataPresent = function (kind) {
  144. if (!this._geometry) {
  145. if (this._delayInfo) {
  146. return this._delayInfo.indexOf(kind) !== -1;
  147. }
  148. return false;
  149. }
  150. return this._geometry.isVerticesDataPresent(kind);
  151. };
  152. Mesh.prototype.getVerticesDataKinds = function () {
  153. if (!this._geometry) {
  154. var result = [];
  155. if (this._delayInfo) {
  156. for (var kind in this._delayInfo) {
  157. result.push(kind);
  158. }
  159. }
  160. return result;
  161. }
  162. return this._geometry.getVerticesDataKinds();
  163. };
  164. Mesh.prototype.getTotalIndices = function () {
  165. if (!this._geometry) {
  166. return 0;
  167. }
  168. return this._geometry.getTotalIndices();
  169. };
  170. Mesh.prototype.getIndices = function () {
  171. if (!this._geometry) {
  172. return [];
  173. }
  174. return this._geometry.getIndices();
  175. };
  176. Mesh.prototype.setPivotMatrix = function (matrix) {
  177. this._pivotMatrix = matrix;
  178. this._cache.pivotMatrixUpdated = true;
  179. };
  180. Mesh.prototype.getPivotMatrix = function () {
  181. return this._pivotMatrix;
  182. };
  183. Mesh.prototype._isSynchronized = function () {
  184. if (this._isDirty) {
  185. return false;
  186. }
  187. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE)
  188. return false;
  189. if (this._cache.pivotMatrixUpdated) {
  190. return false;
  191. }
  192. if (this.infiniteDistance) {
  193. return false;
  194. }
  195. if (!this._cache.position.equals(this.position))
  196. return false;
  197. if (this.rotationQuaternion) {
  198. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  199. return false;
  200. } else {
  201. if (!this._cache.rotation.equals(this.rotation))
  202. return false;
  203. }
  204. if (!this._cache.scaling.equals(this.scaling))
  205. return false;
  206. return true;
  207. };
  208. Mesh.prototype.isReady = function () {
  209. return this._isReady;
  210. };
  211. Mesh.prototype.isAnimated = function () {
  212. return this._animationStarted;
  213. };
  214. Mesh.prototype.isDisposed = function () {
  215. return this._isDisposed;
  216. };
  217. // Methods
  218. Mesh.prototype._initCache = function () {
  219. _super.prototype._initCache.call(this);
  220. this._cache.localMatrixUpdated = false;
  221. this._cache.position = BABYLON.Vector3.Zero();
  222. this._cache.scaling = BABYLON.Vector3.Zero();
  223. this._cache.rotation = BABYLON.Vector3.Zero();
  224. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  225. };
  226. Mesh.prototype.markAsDirty = function (property) {
  227. if (property === "rotation") {
  228. this.rotationQuaternion = null;
  229. }
  230. this._currentRenderId = Number.MAX_VALUE;
  231. this._isDirty = true;
  232. };
  233. Mesh.prototype.refreshBoundingInfo = function () {
  234. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  235. if (data) {
  236. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  237. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  238. }
  239. if (this.subMeshes) {
  240. for (var index = 0; index < this.subMeshes.length; index++) {
  241. this.subMeshes[index].refreshBoundingInfo();
  242. }
  243. }
  244. this._updateBoundingInfo();
  245. };
  246. Mesh.prototype._updateBoundingInfo = function () {
  247. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this._absolutePosition, this._absolutePosition);
  248. this._boundingInfo._update(this._worldMatrix);
  249. if (!this.subMeshes) {
  250. return;
  251. }
  252. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  253. var subMesh = this.subMeshes[subIndex];
  254. subMesh.updateBoundingInfo(this._worldMatrix);
  255. }
  256. };
  257. Mesh.prototype.computeWorldMatrix = function (force) {
  258. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  259. return this._worldMatrix;
  260. }
  261. this._cache.position.copyFrom(this.position);
  262. this._cache.scaling.copyFrom(this.scaling);
  263. this._cache.pivotMatrixUpdated = false;
  264. this._currentRenderId = this.getScene().getRenderId();
  265. this._isDirty = false;
  266. // Scaling
  267. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  268. // Rotation
  269. if (this.rotationQuaternion) {
  270. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  271. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  272. } else {
  273. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  274. this._cache.rotation.copyFrom(this.rotation);
  275. }
  276. // Translation
  277. if (this.infiniteDistance && !this.parent) {
  278. var camera = this.getScene().activeCamera;
  279. var cameraWorldMatrix = camera.getWorldMatrix();
  280. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  281. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  282. } else {
  283. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  284. }
  285. // Composing transformations
  286. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  287. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  288. // Billboarding
  289. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE) {
  290. var localPosition = this.position.clone();
  291. var zero = this.getScene().activeCamera.position.clone();
  292. if (this.parent && this.parent.position) {
  293. localPosition.addInPlace(this.parent.position);
  294. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  295. }
  296. if ((this.billboardMode & Mesh.BILLBOARDMODE_ALL) === Mesh.BILLBOARDMODE_ALL) {
  297. zero = this.getScene().activeCamera.position;
  298. } else {
  299. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  300. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  301. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  302. zero.y = localPosition.y + 0.001;
  303. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  304. zero.z = localPosition.z + 0.001;
  305. }
  306. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  307. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  308. this._localBillboard.invert();
  309. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  310. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  311. }
  312. // Local world
  313. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  314. // Parent
  315. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  316. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  317. } else {
  318. this._worldMatrix.copyFrom(this._localWorld);
  319. }
  320. // Bounding info
  321. this._updateBoundingInfo();
  322. // Absolute position
  323. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  324. return this._worldMatrix;
  325. };
  326. Mesh.prototype._createGlobalSubMesh = function () {
  327. var totalVertices = this.getTotalVertices();
  328. if (!totalVertices || !this.getIndices()) {
  329. return null;
  330. }
  331. this.subMeshes = [];
  332. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  333. };
  334. Mesh.prototype.subdivide = function (count) {
  335. if (count < 1) {
  336. return;
  337. }
  338. var totalIndices = this.getTotalIndices();
  339. var subdivisionSize = totalIndices / count;
  340. var offset = 0;
  341. this.subMeshes = [];
  342. for (var index = 0; index < count; index++) {
  343. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  344. offset += subdivisionSize;
  345. }
  346. };
  347. Mesh.prototype.setVerticesData = function (data, kind, updatable) {
  348. if (!this._geometry) {
  349. var vertexData = new BABYLON.VertexData();
  350. vertexData.set(data, kind);
  351. var scene = this.getScene();
  352. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene.getEngine(), vertexData, updatable, this);
  353. } else {
  354. this._geometry.setVerticesData(data, kind, updatable);
  355. }
  356. };
  357. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  358. if (!this._geometry) {
  359. return;
  360. }
  361. if (!makeItUnique) {
  362. this._geometry.updateVerticesData(kind, data, updateExtends);
  363. } else {
  364. this.makeGeometryUnique();
  365. this.updateVerticesData(kind, data, updateExtends, false);
  366. }
  367. };
  368. Mesh.prototype.makeGeometryUnique = function () {
  369. if (!this._geometry) {
  370. return;
  371. }
  372. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  373. geometry.applyToMesh(this);
  374. };
  375. Mesh.prototype.setIndices = function (indices) {
  376. if (!this._geometry) {
  377. var vertexData = new BABYLON.VertexData();
  378. vertexData.indices = indices;
  379. var scene = this.getScene();
  380. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene.getEngine(), vertexData, false, this);
  381. } else {
  382. this._geometry.setIndices(indices);
  383. }
  384. };
  385. // ANY
  386. Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  387. if (!this._geometry) {
  388. return;
  389. }
  390. var engine = this.getScene().getEngine();
  391. // Wireframe
  392. var indexToBind = this._geometry.getIndexBuffer();
  393. var useTriangles = true;
  394. if (wireframe) {
  395. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  396. useTriangles = false;
  397. }
  398. // VBOs
  399. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  400. // Draw order
  401. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  402. };
  403. Mesh.prototype.registerBeforeRender = function (func) {
  404. this._onBeforeRenderCallbacks.push(func);
  405. };
  406. Mesh.prototype.unregisterBeforeRender = function (func) {
  407. var index = this._onBeforeRenderCallbacks.indexOf(func);
  408. if (index > -1) {
  409. this._onBeforeRenderCallbacks.splice(index, 1);
  410. }
  411. };
  412. Mesh.prototype.render = function (subMesh) {
  413. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  414. return;
  415. }
  416. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  417. this._onBeforeRenderCallbacks[callbackIndex]();
  418. }
  419. // World
  420. var world = this.getWorldMatrix();
  421. // Material
  422. var effectiveMaterial = subMesh.getMaterial();
  423. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  424. return;
  425. }
  426. effectiveMaterial._preBind();
  427. effectiveMaterial.bind(world, this);
  428. // Bind and draw
  429. var engine = this.getScene().getEngine();
  430. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  431. // Unbind
  432. effectiveMaterial.unbind();
  433. };
  434. Mesh.prototype.getEmittedParticleSystems = function () {
  435. var results = new Array();
  436. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  437. var particleSystem = this.getScene().particleSystems[index];
  438. if (particleSystem.emitter === this) {
  439. results.push(particleSystem);
  440. }
  441. }
  442. return results;
  443. };
  444. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  445. var results = new Array();
  446. var descendants = this.getDescendants();
  447. descendants.push(this);
  448. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  449. var particleSystem = this.getScene().particleSystems[index];
  450. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  451. results.push(particleSystem);
  452. }
  453. }
  454. return results;
  455. };
  456. Mesh.prototype.getChildren = function () {
  457. var results = [];
  458. for (var index = 0; index < this.getScene().meshes.length; index++) {
  459. var mesh = this.getScene().meshes[index];
  460. if (mesh.parent == this) {
  461. results.push(mesh);
  462. }
  463. }
  464. return results;
  465. };
  466. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  467. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  468. return false;
  469. }
  470. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  471. return false;
  472. }
  473. var that = this;
  474. var scene = this.getScene();
  475. if (this._geometry) {
  476. this._geometry.load(scene);
  477. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  478. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  479. scene._addPendingData(that);
  480. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  481. that._delayLoadingFunction(JSON.parse(data), that);
  482. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  483. scene._removePendingData(that);
  484. }, function () {
  485. }, scene.database);
  486. }
  487. return true;
  488. };
  489. Mesh.prototype.setMaterialByID = function (id) {
  490. var materials = this.getScene().materials;
  491. for (var index = 0; index < materials.length; index++) {
  492. if (materials[index].id == id) {
  493. this.material = materials[index];
  494. return;
  495. }
  496. }
  497. // Multi
  498. var multiMaterials = this.getScene().multiMaterials;
  499. for (index = 0; index < multiMaterials.length; index++) {
  500. if (multiMaterials[index].id == id) {
  501. this.material = multiMaterials[index];
  502. return;
  503. }
  504. }
  505. };
  506. Mesh.prototype.getAnimatables = function () {
  507. var results = [];
  508. if (this.material) {
  509. results.push(this.material);
  510. }
  511. return results;
  512. };
  513. // Geometry
  514. Mesh.prototype.setPositionWithLocalVector = function (vector3) {
  515. this.computeWorldMatrix();
  516. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  517. };
  518. Mesh.prototype.getPositionExpressedInLocalSpace = function () {
  519. this.computeWorldMatrix();
  520. var invLocalWorldMatrix = this._localWorld.clone();
  521. invLocalWorldMatrix.invert();
  522. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  523. };
  524. Mesh.prototype.locallyTranslate = function (vector3) {
  525. this.computeWorldMatrix();
  526. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  527. };
  528. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  529. // Position
  530. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  531. return;
  532. }
  533. this._resetPointsArrayCache();
  534. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  535. var temp = [];
  536. for (var index = 0; index < data.length; index += 3) {
  537. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  538. }
  539. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  540. // Normals
  541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  542. return;
  543. }
  544. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  545. for (index = 0; index < data.length; index += 3) {
  546. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  547. }
  548. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  549. };
  550. Mesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  551. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  552. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  553. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  554. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  555. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  556. /// <returns>Mesh oriented towards targetMesh</returns>
  557. yawCor = yawCor || 0; // default to zero if undefined
  558. pitchCor = pitchCor || 0;
  559. rollCor = rollCor || 0;
  560. var dv = targetPoint.subtract(this.position);
  561. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  562. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  563. var pitch = Math.atan2(dv.y, len);
  564. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  565. };
  566. // Cache
  567. Mesh.prototype._resetPointsArrayCache = function () {
  568. this._positions = null;
  569. };
  570. Mesh.prototype._generatePointsArray = function () {
  571. if (this._positions)
  572. return;
  573. this._positions = [];
  574. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  575. for (var index = 0; index < data.length; index += 3) {
  576. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  577. }
  578. };
  579. // Collisions
  580. Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  581. this._generatePointsArray();
  582. // Transformation
  583. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  584. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  585. subMesh._lastColliderWorldVertices = [];
  586. subMesh._trianglePlanes = [];
  587. var start = subMesh.verticesStart;
  588. var end = (subMesh.verticesStart + subMesh.verticesCount);
  589. for (var i = start; i < end; i++) {
  590. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  591. }
  592. }
  593. // Collide
  594. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  595. };
  596. Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  597. for (var index = 0; index < this.subMeshes.length; index++) {
  598. var subMesh = this.subMeshes[index];
  599. // Bounding test
  600. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  601. continue;
  602. this._collideForSubMesh(subMesh, transformMatrix, collider);
  603. }
  604. };
  605. Mesh.prototype._checkCollision = function (collider) {
  606. // Bounding box test
  607. if (!this._boundingInfo._checkCollision(collider))
  608. return;
  609. // Transformation matrix
  610. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  611. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  612. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  613. };
  614. Mesh.prototype.intersectsMesh = function (mesh, precise) {
  615. if (!this._boundingInfo || !mesh._boundingInfo) {
  616. return false;
  617. }
  618. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  619. };
  620. Mesh.prototype.intersectsPoint = function (point) {
  621. if (!this._boundingInfo) {
  622. return false;
  623. }
  624. return this._boundingInfo.intersectsPoint(point);
  625. };
  626. // Picking
  627. Mesh.prototype.intersects = function (ray, fastCheck) {
  628. var pickingInfo = new BABYLON.PickingInfo();
  629. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  630. return pickingInfo;
  631. }
  632. this._generatePointsArray();
  633. var intersectInfo = null;
  634. for (var index = 0; index < this.subMeshes.length; index++) {
  635. var subMesh = this.subMeshes[index];
  636. // Bounding test
  637. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  638. continue;
  639. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  640. if (currentIntersectInfo) {
  641. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  642. intersectInfo = currentIntersectInfo;
  643. if (fastCheck) {
  644. break;
  645. }
  646. }
  647. }
  648. }
  649. if (intersectInfo) {
  650. // Get picked point
  651. var world = this.getWorldMatrix();
  652. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  653. var direction = ray.direction.clone();
  654. direction.normalize();
  655. direction = direction.scale(intersectInfo.distance);
  656. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  657. var pickedPoint = worldOrigin.add(worldDirection);
  658. // Return result
  659. pickingInfo.hit = true;
  660. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  661. pickingInfo.pickedPoint = pickedPoint;
  662. pickingInfo.pickedMesh = this;
  663. pickingInfo.bu = intersectInfo.bu;
  664. pickingInfo.bv = intersectInfo.bv;
  665. pickingInfo.faceId = intersectInfo.faceId;
  666. return pickingInfo;
  667. }
  668. return pickingInfo;
  669. };
  670. // Clone
  671. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  672. var result = new BABYLON.Mesh(name, this.getScene());
  673. // Geometry
  674. this._geometry.applyToMesh(result);
  675. // Deep copy
  676. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  677. // Bounding info
  678. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  679. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  680. // Material
  681. result.material = this.material;
  682. // Parent
  683. if (newParent) {
  684. result.parent = newParent;
  685. }
  686. if (!doNotCloneChildren) {
  687. for (var index = 0; index < this.getScene().meshes.length; index++) {
  688. var mesh = this.getScene().meshes[index];
  689. if (mesh.parent == this) {
  690. mesh.clone(mesh.name, result);
  691. }
  692. }
  693. }
  694. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  695. var system = this.getScene().particleSystems[index];
  696. if (system.emitter == this) {
  697. system.clone(system.name, result);
  698. }
  699. }
  700. result.computeWorldMatrix(true);
  701. return result;
  702. };
  703. // Dispose
  704. Mesh.prototype.dispose = function (doNotRecurse) {
  705. if (this._geometry) {
  706. this._geometry.releaseForMesh(this);
  707. }
  708. // Physics
  709. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  710. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  711. }
  712. // Remove from scene
  713. var index = this.getScene().meshes.indexOf(this);
  714. this.getScene().meshes.splice(index, 1);
  715. if (!doNotRecurse) {
  716. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  717. if (this.getScene().particleSystems[index].emitter == this) {
  718. this.getScene().particleSystems[index].dispose();
  719. index--;
  720. }
  721. }
  722. // Children
  723. var objects = this.getScene().meshes.slice(0);
  724. for (index = 0; index < objects.length; index++) {
  725. if (objects[index].parent == this) {
  726. objects[index].dispose();
  727. }
  728. }
  729. } else {
  730. for (index = 0; index < this.getScene().meshes.length; index++) {
  731. var obj = this.getScene().meshes[index];
  732. if (obj.parent === this) {
  733. obj.parent = null;
  734. obj.computeWorldMatrix(true);
  735. }
  736. }
  737. }
  738. this._isDisposed = true;
  739. // Callback
  740. if (this.onDispose) {
  741. this.onDispose();
  742. }
  743. };
  744. // Physics
  745. Mesh.prototype.setPhysicsState = function (impostor, options) {
  746. var physicsEngine = this.getScene().getPhysicsEngine();
  747. if (!physicsEngine) {
  748. return;
  749. }
  750. if (impostor.impostor) {
  751. // Old API
  752. options = impostor;
  753. impostor = impostor.impostor;
  754. }
  755. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  756. options.mass = options.mass || 0;
  757. options.friction = options.friction || 0.2;
  758. options.restitution = options.restitution || 0.9;
  759. this._physicImpostor = impostor;
  760. this._physicsMass = options.mass;
  761. this._physicsFriction = options.friction;
  762. this._physicRestitution = options.restitution;
  763. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  764. physicsEngine._unregisterMesh(this);
  765. return;
  766. }
  767. physicsEngine._registerMesh(this, impostor, options);
  768. };
  769. Mesh.prototype.getPhysicsImpostor = function () {
  770. if (!this._physicImpostor) {
  771. return BABYLON.PhysicsEngine.NoImpostor;
  772. }
  773. return this._physicImpostor;
  774. };
  775. Mesh.prototype.getPhysicsMass = function () {
  776. if (!this._physicsMass) {
  777. return 0;
  778. }
  779. return this._physicsMass;
  780. };
  781. Mesh.prototype.getPhysicsFriction = function () {
  782. if (!this._physicsFriction) {
  783. return 0;
  784. }
  785. return this._physicsFriction;
  786. };
  787. Mesh.prototype.getPhysicsRestitution = function () {
  788. if (!this._physicRestitution) {
  789. return 0;
  790. }
  791. return this._physicRestitution;
  792. };
  793. Mesh.prototype.applyImpulse = function (force, contactPoint) {
  794. if (!this._physicImpostor) {
  795. return;
  796. }
  797. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  798. };
  799. Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
  800. if (!this._physicImpostor) {
  801. return;
  802. }
  803. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2);
  804. };
  805. // Geometric tools
  806. Mesh.prototype.convertToFlatShadedMesh = function () {
  807. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  808. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  809. var kinds = this.getVerticesDataKinds();
  810. var vbs = [];
  811. var data = [];
  812. var newdata = [];
  813. var updatableNormals = false;
  814. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  815. var kind = kinds[kindIndex];
  816. var vertexBuffer = this.getVertexBuffer(kind);
  817. if (kind === BABYLON.VertexBuffer.NormalKind) {
  818. updatableNormals = vertexBuffer.isUpdatable();
  819. kinds.splice(kindIndex, 1);
  820. kindIndex--;
  821. continue;
  822. }
  823. vbs[kind] = vertexBuffer;
  824. data[kind] = vbs[kind].getData();
  825. newdata[kind] = [];
  826. }
  827. // Save previous submeshes
  828. var previousSubmeshes = this.subMeshes.slice(0);
  829. var indices = this.getIndices();
  830. var totalIndices = this.getTotalIndices();
  831. for (index = 0; index < totalIndices; index++) {
  832. var vertexIndex = indices[index];
  833. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  834. kind = kinds[kindIndex];
  835. var stride = vbs[kind].getStrideSize();
  836. for (var offset = 0; offset < stride; offset++) {
  837. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  838. }
  839. }
  840. }
  841. // Updating faces & normal
  842. var normals = [];
  843. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  844. for (var index = 0; index < totalIndices; index += 3) {
  845. indices[index] = index;
  846. indices[index + 1] = index + 1;
  847. indices[index + 2] = index + 2;
  848. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  849. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  850. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  851. var p1p2 = p1.subtract(p2);
  852. var p3p2 = p3.subtract(p2);
  853. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  854. for (var localIndex = 0; localIndex < 3; localIndex++) {
  855. normals.push(normal.x);
  856. normals.push(normal.y);
  857. normals.push(normal.z);
  858. }
  859. }
  860. this.setIndices(indices);
  861. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  862. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  863. kind = kinds[kindIndex];
  864. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  865. }
  866. // Updating submeshes
  867. this.subMeshes = [];
  868. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  869. var previousOne = previousSubmeshes[submeshIndex];
  870. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  871. }
  872. };
  873. // Statics
  874. Mesh.CreateBox = function (name, size, scene, updatable) {
  875. var box = new BABYLON.Mesh(name, scene);
  876. var vertexData = BABYLON.VertexData.CreateBox(size);
  877. vertexData.applyToMesh(box, updatable);
  878. return box;
  879. };
  880. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  881. var sphere = new BABYLON.Mesh(name, scene);
  882. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  883. vertexData.applyToMesh(sphere, updatable);
  884. return sphere;
  885. };
  886. // Cylinder and cone (Code inspired by SharpDX.org)
  887. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
  888. var cylinder = new BABYLON.Mesh(name, scene);
  889. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  890. vertexData.applyToMesh(cylinder, updatable);
  891. return cylinder;
  892. };
  893. // Torus (Code from SharpDX.org)
  894. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  895. var torus = new BABYLON.Mesh(name, scene);
  896. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  897. vertexData.applyToMesh(torus, updatable);
  898. return torus;
  899. };
  900. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  901. var torusKnot = new BABYLON.Mesh(name, scene);
  902. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  903. vertexData.applyToMesh(torusKnot, updatable);
  904. return torusKnot;
  905. };
  906. // Plane & ground
  907. Mesh.CreatePlane = function (name, size, scene, updatable) {
  908. var plane = new BABYLON.Mesh(name, scene);
  909. var vertexData = BABYLON.VertexData.CreatePlane(size);
  910. vertexData.applyToMesh(plane, updatable);
  911. return plane;
  912. };
  913. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  914. var ground = new BABYLON.Mesh(name, scene);
  915. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  916. vertexData.applyToMesh(ground, updatable);
  917. return ground;
  918. };
  919. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  920. var ground = new BABYLON.Mesh(name, scene);
  921. var onload = function (img) {
  922. // Getting height map data
  923. var canvas = document.createElement("canvas");
  924. var context = canvas.getContext("2d");
  925. var heightMapWidth = img.width;
  926. var heightMapHeight = img.height;
  927. canvas.width = heightMapWidth;
  928. canvas.height = heightMapHeight;
  929. context.drawImage(img, 0, 0);
  930. // Create VertexData from map data
  931. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  932. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  933. vertexData.applyToMesh(ground, updatable);
  934. ground._isReady = true;
  935. };
  936. BABYLON.Tools.LoadImage(url, onload, function () {
  937. }, scene.database);
  938. ground._isReady = false;
  939. return ground;
  940. };
  941. // Tools
  942. Mesh.MinMax = function (meshes) {
  943. var minVector = null;
  944. var maxVector = null;
  945. for (var i in meshes) {
  946. var mesh = meshes[i];
  947. var boundingBox = mesh.getBoundingInfo().boundingBox;
  948. if (!minVector) {
  949. minVector = boundingBox.minimumWorld;
  950. maxVector = boundingBox.maximumWorld;
  951. continue;
  952. }
  953. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  954. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  955. }
  956. return {
  957. min: minVector,
  958. max: maxVector
  959. };
  960. };
  961. Mesh.Center = function (meshesOrMinMaxVector) {
  962. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  963. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  964. };
  965. Mesh.BILLBOARDMODE_NONE = 0;
  966. Mesh.BILLBOARDMODE_X = 1;
  967. Mesh.BILLBOARDMODE_Y = 2;
  968. Mesh.BILLBOARDMODE_Z = 4;
  969. Mesh.BILLBOARDMODE_ALL = 7;
  970. return Mesh;
  971. })(BABYLON.Node);
  972. BABYLON.Mesh = Mesh;
  973. })(BABYLON || (BABYLON = {}));
  974. //# sourceMappingURL=babylon.mesh.js.map