babylon.mesh.ts 46 KB

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