babylon.abstractMesh.ts 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  1. module BABYLON {
  2. export class AbstractMesh extends Node implements IDisposable, ICullable, 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 AbstractMesh._BILLBOARDMODE_NONE;
  11. }
  12. public static get BILLBOARDMODE_X(): number {
  13. return AbstractMesh._BILLBOARDMODE_X;
  14. }
  15. public static get BILLBOARDMODE_Y(): number {
  16. return AbstractMesh._BILLBOARDMODE_Y;
  17. }
  18. public static get BILLBOARDMODE_Z(): number {
  19. return AbstractMesh._BILLBOARDMODE_Z;
  20. }
  21. public static get BILLBOARDMODE_ALL(): number {
  22. return AbstractMesh._BILLBOARDMODE_ALL;
  23. }
  24. // facetData private properties
  25. private _facetPositions: Vector3[]; // facet local positions
  26. private _facetNormals: Vector3[]; // facet local normals
  27. private _facetPartitioning: number[][]; // partitioning array of facet index arrays
  28. private _facetNb: number = 0; // facet number
  29. private _partitioningSubdivisions: number = 10; // number of subdivisions per axis in the partioning space
  30. private _partitioningBBoxRatio: number = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  31. private _facetDataEnabled: boolean = false; // is the facet data feature enabled on this mesh ?
  32. private _facetParameters: any = {}; // keep a reference to the object parameters to avoid memory re-allocation
  33. private _bbSize: Vector3 = Vector3.Zero(); // bbox size approximated for facet data
  34. private _subDiv = { // actual number of subdivisions per axis for ComputeNormals()
  35. max: 1,
  36. X: 1,
  37. Y: 1,
  38. Z: 1
  39. };
  40. /**
  41. * Read-only : the number of facets in the mesh
  42. */
  43. public get facetNb(): number {
  44. return this._facetNb;
  45. }
  46. /**
  47. * The number (integer) of subdivisions per axis in the partioning space
  48. */
  49. public get partitioningSubdivisions(): number {
  50. return this._partitioningSubdivisions;
  51. }
  52. public set partitioningSubdivisions(nb: number) {
  53. this._partitioningSubdivisions = nb;
  54. }
  55. /**
  56. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  57. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  58. */
  59. public get partitioningBBoxRatio(): number {
  60. return this._partitioningBBoxRatio;
  61. }
  62. public set partitioningBBoxRatio(ratio: number) {
  63. this._partitioningBBoxRatio = ratio;
  64. }
  65. /**
  66. * Read-only boolean : is the feature facetData enabled ?
  67. */
  68. public get isFacetDataEnabled(): boolean {
  69. return this._facetDataEnabled;
  70. }
  71. // Events
  72. /**
  73. * An event triggered when this mesh collides with another one
  74. * @type {BABYLON.Observable}
  75. */
  76. public onCollideObservable = new Observable<AbstractMesh>();
  77. private _onCollideObserver: Observer<AbstractMesh>;
  78. public set onCollide(callback: () => void) {
  79. if (this._onCollideObserver) {
  80. this.onCollideObservable.remove(this._onCollideObserver);
  81. }
  82. this._onCollideObserver = this.onCollideObservable.add(callback);
  83. }
  84. /**
  85. * An event triggered when the collision's position changes
  86. * @type {BABYLON.Observable}
  87. */
  88. public onCollisionPositionChangeObservable = new Observable<Vector3>();
  89. private _onCollisionPositionChangeObserver: Observer<Vector3>;
  90. public set onCollisionPositionChange(callback: () => void) {
  91. if (this._onCollisionPositionChangeObserver) {
  92. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  93. }
  94. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  95. }
  96. /**
  97. * An event triggered after the world matrix is updated
  98. * @type {BABYLON.Observable}
  99. */
  100. public onAfterWorldMatrixUpdateObservable = new Observable<AbstractMesh>();
  101. // Properties
  102. public definedFacingForward = true; // orientation for POV movement & rotation
  103. public position = new Vector3(0.0, 0.0, 0.0);
  104. private _rotation = new Vector3(0.0, 0.0, 0.0);
  105. private _rotationQuaternion: Quaternion;
  106. private _scaling = new Vector3(1.0, 1.0, 1.0);
  107. public billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  108. public visibility = 1.0;
  109. public alphaIndex = Number.MAX_VALUE;
  110. public infiniteDistance = false;
  111. public isVisible = true;
  112. public isPickable = true;
  113. public showBoundingBox = false;
  114. public showSubMeshesBoundingBox = false;
  115. public isBlocker = false;
  116. public renderingGroupId = 0;
  117. private _material: Material
  118. public get material(): Material {
  119. return this._material;
  120. }
  121. public set material(value: Material) {
  122. if (this._material === value) {
  123. return;
  124. }
  125. this._material = value;
  126. if (!this.subMeshes) {
  127. return;
  128. }
  129. for (var subMesh of this.subMeshes) {
  130. subMesh.setEffect(null);
  131. }
  132. }
  133. private _receiveShadows = false;
  134. public get receiveShadows(): boolean {
  135. return this._receiveShadows;
  136. }
  137. public set receiveShadows(value: boolean) {
  138. if (this._receiveShadows === value) {
  139. return;
  140. }
  141. this._receiveShadows = value;
  142. this._markSubMeshesAsLightDirty();
  143. }
  144. public renderOutline = false;
  145. public outlineColor = Color3.Red();
  146. public outlineWidth = 0.02;
  147. public renderOverlay = false;
  148. public overlayColor = Color3.Red();
  149. public overlayAlpha = 0.5;
  150. private _hasVertexAlpha = false;
  151. public get hasVertexAlpha(): boolean {
  152. return this._hasVertexAlpha;
  153. }
  154. public set hasVertexAlpha(value: boolean) {
  155. if (this._hasVertexAlpha === value) {
  156. return;
  157. }
  158. this._hasVertexAlpha = value;
  159. this._markSubMeshesAsAttributesDirty();
  160. }
  161. private _useVertexColors = true;
  162. public get useVertexColors(): boolean {
  163. return this._useVertexColors;
  164. }
  165. public set useVertexColors(value: boolean) {
  166. if (this._useVertexColors === value) {
  167. return;
  168. }
  169. this._useVertexColors = value;
  170. this._markSubMeshesAsAttributesDirty();
  171. }
  172. private _computeBonesUsingShaders = true;
  173. public get computeBonesUsingShaders(): boolean {
  174. return this._computeBonesUsingShaders;
  175. }
  176. public set computeBonesUsingShaders(value: boolean) {
  177. if (this._computeBonesUsingShaders === value) {
  178. return;
  179. }
  180. this._computeBonesUsingShaders = value;
  181. this._markSubMeshesAsAttributesDirty();
  182. }
  183. private _numBoneInfluencers = 4;
  184. public get numBoneInfluencers(): number {
  185. return this._numBoneInfluencers;
  186. }
  187. public set numBoneInfluencers(value: number) {
  188. if (this._numBoneInfluencers === value) {
  189. return;
  190. }
  191. this._numBoneInfluencers = value;
  192. this._markSubMeshesAsAttributesDirty();
  193. }
  194. private _applyFog = true;
  195. public get applyFog(): boolean {
  196. return this._applyFog;
  197. }
  198. public set applyFog(value: boolean) {
  199. if (this._applyFog === value) {
  200. return;
  201. }
  202. this._applyFog = value;
  203. this._markSubMeshesAsMiscDirty();
  204. }
  205. public scalingDeterminant = 1;
  206. public useOctreeForRenderingSelection = true;
  207. public useOctreeForPicking = true;
  208. public useOctreeForCollisions = true;
  209. public layerMask: number = 0x0FFFFFFF;
  210. /**
  211. * True if the mesh must be rendered in any case.
  212. */
  213. public alwaysSelectAsActiveMesh = false;
  214. /**
  215. * This scene's action manager
  216. * @type {BABYLON.ActionManager}
  217. */
  218. public actionManager: ActionManager;
  219. // Physics
  220. public physicsImpostor: BABYLON.PhysicsImpostor;
  221. // Collisions
  222. private _checkCollisions = false;
  223. private _collisionMask = -1;
  224. private _collisionGroup = -1;
  225. public ellipsoid = new Vector3(0.5, 1, 0.5);
  226. public ellipsoidOffset = new Vector3(0, 0, 0);
  227. private _collider: Collider;
  228. private _oldPositionForCollisions = new Vector3(0, 0, 0);
  229. private _diffPositionForCollisions = new Vector3(0, 0, 0);
  230. private _newPositionForCollisions = new Vector3(0, 0, 0);
  231. public get collisionMask(): number {
  232. return this._collisionMask;
  233. }
  234. public set collisionMask(mask: number) {
  235. this._collisionMask = !isNaN(mask) ? mask : -1;
  236. }
  237. public get collisionGroup(): number {
  238. return this._collisionGroup;
  239. }
  240. public set collisionGroup(mask: number) {
  241. this._collisionGroup = !isNaN(mask) ? mask : -1;
  242. }
  243. // Attach to bone
  244. private _meshToBoneReferal: AbstractMesh;
  245. // Edges
  246. public edgesWidth = 1;
  247. public edgesColor = new Color4(1, 0, 0, 1);
  248. public _edgesRenderer: EdgesRenderer;
  249. // Cache
  250. private _localWorld = Matrix.Zero();
  251. public _worldMatrix = Matrix.Zero();
  252. private _absolutePosition = Vector3.Zero();
  253. private _collisionsTransformMatrix = Matrix.Zero();
  254. private _collisionsScalingMatrix = Matrix.Zero();
  255. private _isDirty = false;
  256. public _masterMesh: AbstractMesh;
  257. public _boundingInfo: BoundingInfo;
  258. private _pivotMatrix = Matrix.Identity();
  259. public _isDisposed = false;
  260. public _renderId = 0;
  261. public subMeshes: SubMesh[];
  262. public _submeshesOctree: Octree<SubMesh>;
  263. public _intersectionsInProgress = new Array<AbstractMesh>();
  264. private _isWorldMatrixFrozen = false;
  265. public _unIndexed = false;
  266. public _poseMatrix: Matrix;
  267. public _lightSources = new Array<Light>();
  268. public get _positions(): Vector3[] {
  269. return null;
  270. }
  271. // Loading properties
  272. public _waitingActions: any;
  273. public _waitingFreezeWorldMatrix: boolean;
  274. // Skeleton
  275. private _skeleton: Skeleton;
  276. public _bonesTransformMatrices: Float32Array;
  277. public set skeleton(value: Skeleton) {
  278. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  279. this._skeleton._unregisterMeshWithPoseMatrix(this);
  280. }
  281. if (value && value.needInitialSkinMatrix) {
  282. value._registerMeshWithPoseMatrix(this);
  283. }
  284. this._skeleton = value;
  285. if (!this._skeleton) {
  286. this._bonesTransformMatrices = null;
  287. }
  288. this._markSubMeshesAsAttributesDirty();
  289. }
  290. public get skeleton(): Skeleton {
  291. return this._skeleton;
  292. }
  293. // Constructor
  294. constructor(name: string, scene: Scene) {
  295. super(name, scene);
  296. this.getScene().addMesh(this);
  297. this._resyncLightSources();
  298. }
  299. /**
  300. * Returns the string "AbstractMesh"
  301. */
  302. public getClassName(): string {
  303. return "AbstractMesh";
  304. }
  305. /**
  306. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  307. */
  308. public toString(fullDetails?: boolean): string {
  309. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof InstancedMesh ? "YES" : "NO");
  310. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  311. if (this._skeleton) {
  312. ret += ", skeleton: " + this._skeleton.name;
  313. }
  314. if (fullDetails) {
  315. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  316. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  317. }
  318. return ret;
  319. }
  320. public _resyncLightSources(): void {
  321. this._lightSources.length = 0;
  322. for (var light of this.getScene().lights) {
  323. if (!light.isEnabled()) {
  324. continue;
  325. }
  326. if (light.canAffectMesh(this)) {
  327. this._lightSources.push(light);
  328. }
  329. }
  330. this._markSubMeshesAsLightDirty();
  331. }
  332. public _resyncLighSource(light: Light): void {
  333. var isIn = light.isEnabled() && light.canAffectMesh(this);
  334. var index = this._lightSources.indexOf(light);
  335. if (index === -1) {
  336. if (!isIn) {
  337. return;
  338. }
  339. this._lightSources.push(light);
  340. } else {
  341. if (isIn) {
  342. return;
  343. }
  344. this._lightSources.splice(index, 1);
  345. }
  346. this._markSubMeshesAsLightDirty();
  347. }
  348. public _removeLightSource(light: Light): void {
  349. var index = this._lightSources.indexOf(light);
  350. if (index === -1) {
  351. return;
  352. }
  353. this._lightSources.splice(index, 1);
  354. }
  355. private _markSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  356. if (!this.subMeshes) {
  357. return;
  358. }
  359. for (var subMesh of this.subMeshes) {
  360. if (subMesh._materialDefines) {
  361. func(subMesh._materialDefines);
  362. }
  363. }
  364. }
  365. public _markSubMeshesAsLightDirty() {
  366. this._markSubMeshesAsDirty(defines => defines.markAsLightDirty());
  367. }
  368. public _markSubMeshesAsAttributesDirty() {
  369. this._markSubMeshesAsDirty(defines => defines.markAsAttributesDirty());
  370. }
  371. public _markSubMeshesAsMiscDirty() {
  372. if (!this.subMeshes) {
  373. return;
  374. }
  375. for (var subMesh of this.subMeshes) {
  376. var material = subMesh.getMaterial();
  377. if (material) {
  378. material.markAsDirty(Material.MiscDirtyFlag);
  379. }
  380. }
  381. }
  382. /**
  383. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  384. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  385. * Default : (0.0, 0.0, 0.0)
  386. */
  387. public get rotation(): Vector3 {
  388. return this._rotation;
  389. }
  390. public set rotation(newRotation: Vector3) {
  391. this._rotation = newRotation;
  392. }
  393. /**
  394. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  395. * Default : (1.0, 1.0, 1.0)
  396. */
  397. public get scaling(): Vector3 {
  398. return this._scaling;
  399. }
  400. public set scaling(newScaling: Vector3) {
  401. this._scaling = newScaling;
  402. if (this.physicsImpostor) {
  403. this.physicsImpostor.forceUpdate();
  404. }
  405. }
  406. /**
  407. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  408. * It's null by default.
  409. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  410. */
  411. public get rotationQuaternion() {
  412. return this._rotationQuaternion;
  413. }
  414. public set rotationQuaternion(quaternion: Quaternion) {
  415. this._rotationQuaternion = quaternion;
  416. //reset the rotation vector.
  417. if (quaternion && this.rotation.length()) {
  418. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  419. }
  420. }
  421. // Methods
  422. /**
  423. * Copies the paramater passed Matrix into the mesh Pose matrix.
  424. * Returns the AbstractMesh.
  425. */
  426. public updatePoseMatrix(matrix: Matrix): AbstractMesh {
  427. this._poseMatrix.copyFrom(matrix);
  428. return this;
  429. }
  430. /**
  431. * Returns the mesh Pose matrix.
  432. * Returned object : Matrix
  433. */
  434. public getPoseMatrix(): Matrix {
  435. return this._poseMatrix;
  436. }
  437. /**
  438. * Disables the mesh edger rendering mode.
  439. * Returns the AbstractMesh.
  440. */
  441. public disableEdgesRendering(): AbstractMesh {
  442. if (this._edgesRenderer !== undefined) {
  443. this._edgesRenderer.dispose();
  444. this._edgesRenderer = undefined;
  445. }
  446. return this;
  447. }
  448. /**
  449. * Enables the edge rendering mode on the mesh.
  450. * This mode makes the mesh edges visible.
  451. * Returns the AbstractMesh.
  452. */
  453. public enableEdgesRendering(epsilon = 0.95, checkVerticesInsteadOfIndices = false): AbstractMesh {
  454. this.disableEdgesRendering();
  455. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  456. return this;
  457. }
  458. /**
  459. * Returns true if the mesh is blocked. Used by the class Mesh.
  460. * Returns the boolean `false` by default.
  461. */
  462. public get isBlocked(): boolean {
  463. return false;
  464. }
  465. /**
  466. * Returns the mesh itself by default, used by the class Mesh.
  467. * Returned type : AbstractMesh
  468. */
  469. public getLOD(camera: Camera): AbstractMesh {
  470. return this;
  471. }
  472. /**
  473. * Returns 0 by default, used by the class Mesh.
  474. * Returns an integer.
  475. */
  476. public getTotalVertices(): number {
  477. return 0;
  478. }
  479. /**
  480. * Returns null by default, used by the class Mesh.
  481. * Returned type : integer array
  482. */
  483. public getIndices(): IndicesArray {
  484. return null;
  485. }
  486. /**
  487. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  488. * Returned type : float array or Float32Array
  489. */
  490. public getVerticesData(kind: string): number[] | Float32Array {
  491. return null;
  492. }
  493. /**
  494. * Sets the vertex data of the mesh geometry for the requested `kind`.
  495. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  496. * The `data` are either a numeric array either a Float32Array.
  497. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  498. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  499. * Note that a new underlying VertexBuffer object is created each call.
  500. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  501. *
  502. * Possible `kind` values :
  503. * - BABYLON.VertexBuffer.PositionKind
  504. * - BABYLON.VertexBuffer.UVKind
  505. * - BABYLON.VertexBuffer.UV2Kind
  506. * - BABYLON.VertexBuffer.UV3Kind
  507. * - BABYLON.VertexBuffer.UV4Kind
  508. * - BABYLON.VertexBuffer.UV5Kind
  509. * - BABYLON.VertexBuffer.UV6Kind
  510. * - BABYLON.VertexBuffer.ColorKind
  511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  515. *
  516. * Returns the Mesh.
  517. */
  518. public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): Mesh {
  519. return null;
  520. }
  521. /**
  522. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  523. * If the mesh has no geometry, it is simply returned as it is.
  524. * The `data` are either a numeric array either a Float32Array.
  525. * No new underlying VertexBuffer object is created.
  526. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  527. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  528. *
  529. * Possible `kind` values :
  530. * - BABYLON.VertexBuffer.PositionKind
  531. * - BABYLON.VertexBuffer.UVKind
  532. * - BABYLON.VertexBuffer.UV2Kind
  533. * - BABYLON.VertexBuffer.UV3Kind
  534. * - BABYLON.VertexBuffer.UV4Kind
  535. * - BABYLON.VertexBuffer.UV5Kind
  536. * - BABYLON.VertexBuffer.UV6Kind
  537. * - BABYLON.VertexBuffer.ColorKind
  538. * - BABYLON.VertexBuffer.MatricesIndicesKind
  539. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  540. * - BABYLON.VertexBuffer.MatricesWeightsKind
  541. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  542. *
  543. * Returns the Mesh.
  544. */
  545. public updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
  546. return null;
  547. }
  548. /**
  549. * Sets the mesh indices.
  550. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  551. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  552. * This method creates a new index buffer each call.
  553. * Returns the Mesh.
  554. */
  555. public setIndices(indices: IndicesArray, totalVertices?: number): Mesh {
  556. return null;
  557. }
  558. /** Returns false by default, used by the class Mesh.
  559. * Returns a boolean
  560. */
  561. public isVerticesDataPresent(kind: string): boolean {
  562. return false;
  563. }
  564. /**
  565. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  566. * Returns a BoundingInfo
  567. */
  568. public getBoundingInfo(): BoundingInfo {
  569. if (this._masterMesh) {
  570. return this._masterMesh.getBoundingInfo();
  571. }
  572. if (!this._boundingInfo) {
  573. this._updateBoundingInfo();
  574. }
  575. return this._boundingInfo;
  576. }
  577. /**
  578. * Sets a mesh new object BoundingInfo.
  579. * Returns the AbstractMesh.
  580. */
  581. public setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh {
  582. this._boundingInfo = boundingInfo;
  583. return this;
  584. }
  585. public get useBones(): boolean {
  586. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind);
  587. }
  588. public _preActivate(): void {
  589. }
  590. public _preActivateForIntermediateRendering(renderId: number): void {
  591. }
  592. public _activate(renderId: number): void {
  593. this._renderId = renderId;
  594. }
  595. /**
  596. * Returns the last update of the World matrix
  597. * Returns a Matrix.
  598. */
  599. public getWorldMatrix(): Matrix {
  600. if (this._masterMesh) {
  601. return this._masterMesh.getWorldMatrix();
  602. }
  603. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  604. this.computeWorldMatrix();
  605. }
  606. return this._worldMatrix;
  607. }
  608. /**
  609. * Returns directly the last state of the mesh World matrix.
  610. * A Matrix is returned.
  611. */
  612. public get worldMatrixFromCache(): Matrix {
  613. return this._worldMatrix;
  614. }
  615. /**
  616. * Returns the current mesh absolute position.
  617. * Retuns a Vector3.
  618. */
  619. public get absolutePosition(): Vector3 {
  620. return this._absolutePosition;
  621. }
  622. /**
  623. * Prevents the World matrix to be computed any longer.
  624. * Returns the AbstractMesh.
  625. */
  626. public freezeWorldMatrix(): AbstractMesh {
  627. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  628. this.computeWorldMatrix(true);
  629. this._isWorldMatrixFrozen = true;
  630. return this;
  631. }
  632. /**
  633. * Allows back the World matrix computation.
  634. * Returns the AbstractMesh.
  635. */
  636. public unfreezeWorldMatrix() {
  637. this._isWorldMatrixFrozen = false;
  638. this.computeWorldMatrix(true);
  639. return this;
  640. }
  641. /**
  642. * True if the World matrix has been frozen.
  643. * Returns a boolean.
  644. */
  645. public get isWorldMatrixFrozen(): boolean {
  646. return this._isWorldMatrixFrozen;
  647. }
  648. private static _rotationAxisCache = new Quaternion();
  649. /**
  650. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  651. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  652. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  653. * The passed axis is also normalized.
  654. * Returns the AbstractMesh.
  655. */
  656. public rotate(axis: Vector3, amount: number, space?: Space): AbstractMesh {
  657. axis.normalize();
  658. if (!this.rotationQuaternion) {
  659. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  660. this.rotation = Vector3.Zero();
  661. }
  662. var rotationQuaternion: Quaternion;
  663. if (!space || (space as any) === Space.LOCAL) {
  664. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  665. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  666. }
  667. else {
  668. if (this.parent) {
  669. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  670. invertParentWorldMatrix.invert();
  671. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  672. }
  673. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  674. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  675. }
  676. return this;
  677. }
  678. /**
  679. * Translates the mesh along the axis vector for the passed distance in the given space.
  680. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  681. * Returns the AbstractMesh.
  682. */
  683. public translate(axis: Vector3, distance: number, space?: Space): AbstractMesh {
  684. var displacementVector = axis.scale(distance);
  685. if (!space || (space as any) === Space.LOCAL) {
  686. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  687. this.setPositionWithLocalVector(tempV3);
  688. }
  689. else {
  690. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  691. }
  692. return this;
  693. }
  694. /**
  695. * Adds a rotation step to the mesh current rotation.
  696. * x, y, z are Euler angles expressed in radians.
  697. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  698. * This means this rotation is made in the mesh local space only.
  699. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  700. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  701. * ```javascript
  702. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  703. * ```
  704. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  705. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  706. * Returns the AbstractMesh.
  707. */
  708. public addRotation(x: number, y: number, z: number): AbstractMesh {
  709. var rotationQuaternion;
  710. if (this.rotationQuaternion) {
  711. rotationQuaternion = this.rotationQuaternion;
  712. }
  713. else {
  714. rotationQuaternion = Tmp.Quaternion[1];
  715. Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  716. }
  717. var accumulation = BABYLON.Tmp.Quaternion[0];
  718. Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  719. rotationQuaternion.multiplyInPlace(accumulation);
  720. if (!this.rotationQuaternion) {
  721. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  722. }
  723. return this;
  724. }
  725. /**
  726. * Retuns the mesh absolute position in the World.
  727. * Returns a Vector3.
  728. */
  729. public getAbsolutePosition(): Vector3 {
  730. this.computeWorldMatrix();
  731. return this._absolutePosition;
  732. }
  733. /**
  734. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  735. * Returns the AbstractMesh.
  736. */
  737. public setAbsolutePosition(absolutePosition: Vector3): AbstractMesh {
  738. if (!absolutePosition) {
  739. return;
  740. }
  741. var absolutePositionX;
  742. var absolutePositionY;
  743. var absolutePositionZ;
  744. if (absolutePosition.x === undefined) {
  745. if (arguments.length < 3) {
  746. return;
  747. }
  748. absolutePositionX = arguments[0];
  749. absolutePositionY = arguments[1];
  750. absolutePositionZ = arguments[2];
  751. }
  752. else {
  753. absolutePositionX = absolutePosition.x;
  754. absolutePositionY = absolutePosition.y;
  755. absolutePositionZ = absolutePosition.z;
  756. }
  757. if (this.parent) {
  758. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  759. invertParentWorldMatrix.invert();
  760. var worldPosition = new Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  761. this.position = Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  762. } else {
  763. this.position.x = absolutePositionX;
  764. this.position.y = absolutePositionY;
  765. this.position.z = absolutePositionZ;
  766. }
  767. return this;
  768. }
  769. // ================================== Point of View Movement =================================
  770. /**
  771. * Perform relative position change from the point of view of behind the front of the mesh.
  772. * This is performed taking into account the meshes current rotation, so you do not have to care.
  773. * Supports definition of mesh facing forward or backward.
  774. * @param {number} amountRight
  775. * @param {number} amountUp
  776. * @param {number} amountForward
  777. *
  778. * Returns the AbstractMesh.
  779. */
  780. public movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh {
  781. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  782. return this;
  783. }
  784. /**
  785. * Calculate relative position change from the point of view of behind the front of the mesh.
  786. * This is performed taking into account the meshes current rotation, so you do not have to care.
  787. * Supports definition of mesh facing forward or backward.
  788. * @param {number} amountRight
  789. * @param {number} amountUp
  790. * @param {number} amountForward
  791. *
  792. * Returns a new Vector3.
  793. */
  794. public calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3 {
  795. var rotMatrix = new Matrix();
  796. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  797. rotQuaternion.toRotationMatrix(rotMatrix);
  798. var translationDelta = Vector3.Zero();
  799. var defForwardMult = this.definedFacingForward ? -1 : 1;
  800. Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  801. return translationDelta;
  802. }
  803. // ================================== Point of View Rotation =================================
  804. /**
  805. * Perform relative rotation change from the point of view of behind the front of the mesh.
  806. * Supports definition of mesh facing forward or backward.
  807. * @param {number} flipBack
  808. * @param {number} twirlClockwise
  809. * @param {number} tiltRight
  810. *
  811. * Returns the AbstractMesh.
  812. */
  813. public rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh {
  814. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  815. return this;
  816. }
  817. /**
  818. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  819. * Supports definition of mesh facing forward or backward.
  820. * @param {number} flipBack
  821. * @param {number} twirlClockwise
  822. * @param {number} tiltRight
  823. *
  824. * Returns a new Vector3.
  825. */
  826. public calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3 {
  827. var defForwardMult = this.definedFacingForward ? 1 : -1;
  828. return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  829. }
  830. /**
  831. * Sets a new pivot matrix to the mesh.
  832. * Returns the AbstractMesh.
  833. */
  834. public setPivotMatrix(matrix: Matrix): AbstractMesh {
  835. this._pivotMatrix = matrix;
  836. this._cache.pivotMatrixUpdated = true;
  837. return this;
  838. }
  839. /**
  840. * Returns the mesh pivot matrix.
  841. * Default : Identity.
  842. * A Matrix is returned.
  843. */
  844. public getPivotMatrix(): Matrix {
  845. return this._pivotMatrix;
  846. }
  847. public _isSynchronized(): boolean {
  848. if (this._isDirty) {
  849. return false;
  850. }
  851. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  852. return false;
  853. if (this._cache.pivotMatrixUpdated) {
  854. return false;
  855. }
  856. if (this.infiniteDistance) {
  857. return false;
  858. }
  859. if (!this._cache.position.equals(this.position))
  860. return false;
  861. if (this.rotationQuaternion) {
  862. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  863. return false;
  864. }
  865. if (!this._cache.rotation.equals(this.rotation))
  866. return false;
  867. if (!this._cache.scaling.equals(this.scaling))
  868. return false;
  869. return true;
  870. }
  871. public _initCache() {
  872. super._initCache();
  873. this._cache.localMatrixUpdated = false;
  874. this._cache.position = Vector3.Zero();
  875. this._cache.scaling = Vector3.Zero();
  876. this._cache.rotation = Vector3.Zero();
  877. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  878. this._cache.billboardMode = -1;
  879. }
  880. public markAsDirty(property: string): AbstractMesh {
  881. if (property === "rotation") {
  882. this.rotationQuaternion = null;
  883. }
  884. this._currentRenderId = Number.MAX_VALUE;
  885. this._isDirty = true;
  886. return this;
  887. }
  888. /**
  889. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  890. * Returns the AbstractMesh.
  891. */
  892. public _updateBoundingInfo(): AbstractMesh {
  893. this._boundingInfo = this._boundingInfo || new BoundingInfo(this.absolutePosition, this.absolutePosition);
  894. this._boundingInfo.update(this.worldMatrixFromCache);
  895. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  896. return this;
  897. }
  898. /**
  899. * Update a mesh's children BoundingInfo objects only.
  900. * Returns the AbstractMesh.
  901. */
  902. public _updateSubMeshesBoundingInfo(matrix: Matrix): AbstractMesh {
  903. if (!this.subMeshes) {
  904. return;
  905. }
  906. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  907. var subMesh = this.subMeshes[subIndex];
  908. if (!subMesh.IsGlobal) {
  909. subMesh.updateBoundingInfo(matrix);
  910. }
  911. }
  912. return this;
  913. }
  914. /**
  915. * Computes the mesh World matrix and returns it.
  916. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  917. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  918. * If the parameter `force`is set to `true`, the actual computation is done.
  919. * Returns the mesh World Matrix.
  920. */
  921. public computeWorldMatrix(force?: boolean): Matrix {
  922. if (this._isWorldMatrixFrozen) {
  923. return this._worldMatrix;
  924. }
  925. if (!force && this.isSynchronized(true)) {
  926. this._currentRenderId = this.getScene().getRenderId();
  927. return this._worldMatrix;
  928. }
  929. this._cache.position.copyFrom(this.position);
  930. this._cache.scaling.copyFrom(this.scaling);
  931. this._cache.pivotMatrixUpdated = false;
  932. this._cache.billboardMode = this.billboardMode;
  933. this._currentRenderId = this.getScene().getRenderId();
  934. this._isDirty = false;
  935. // Scaling
  936. Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, Tmp.Matrix[1]);
  937. // Rotation
  938. //rotate, if quaternion is set and rotation was used
  939. if (this.rotationQuaternion) {
  940. var len = this.rotation.length();
  941. if (len) {
  942. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z))
  943. this.rotation.copyFromFloats(0, 0, 0);
  944. }
  945. }
  946. if (this.rotationQuaternion) {
  947. this.rotationQuaternion.toRotationMatrix(Tmp.Matrix[0]);
  948. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  949. } else {
  950. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, Tmp.Matrix[0]);
  951. this._cache.rotation.copyFrom(this.rotation);
  952. }
  953. // Translation
  954. if (this.infiniteDistance && !this.parent) {
  955. var camera = this.getScene().activeCamera;
  956. if (camera) {
  957. var cameraWorldMatrix = camera.getWorldMatrix();
  958. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  959. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  960. this.position.z + cameraGlobalPosition.z, Tmp.Matrix[2]);
  961. }
  962. } else {
  963. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, Tmp.Matrix[2]);
  964. }
  965. // Composing transformations
  966. this._pivotMatrix.multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  967. Tmp.Matrix[4].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  968. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  969. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  970. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  971. // Need to decompose each rotation here
  972. var currentPosition = Tmp.Vector3[3];
  973. if (this.parent && this.parent.getWorldMatrix) {
  974. if (this._meshToBoneReferal) {
  975. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  976. Vector3.TransformCoordinatesToRef(this.position, Tmp.Matrix[6], currentPosition);
  977. } else {
  978. Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  979. }
  980. } else {
  981. currentPosition.copyFrom(this.position);
  982. }
  983. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  984. var finalEuler = Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  985. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X)
  986. {
  987. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  988. }
  989. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y)
  990. {
  991. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  992. }
  993. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z)
  994. {
  995. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  996. }
  997. Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, Tmp.Matrix[0]);
  998. } else {
  999. Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  1000. Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  1001. Tmp.Matrix[1].invertToRef(Tmp.Matrix[0]);
  1002. }
  1003. Tmp.Matrix[1].copyFrom(Tmp.Matrix[5]);
  1004. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  1005. }
  1006. // Local world
  1007. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], this._localWorld);
  1008. // Parent
  1009. if (this.parent && this.parent.getWorldMatrix) {
  1010. this._markSyncedWithParent();
  1011. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  1012. if (this._meshToBoneReferal) {
  1013. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  1014. Tmp.Matrix[5].copyFrom(Tmp.Matrix[6]);
  1015. } else {
  1016. Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  1017. }
  1018. this._localWorld.getTranslationToRef(Tmp.Vector3[5]);
  1019. Vector3.TransformCoordinatesToRef(Tmp.Vector3[5], Tmp.Matrix[5], Tmp.Vector3[5]);
  1020. this._worldMatrix.copyFrom(this._localWorld);
  1021. this._worldMatrix.setTranslation(Tmp.Vector3[5]);
  1022. } else {
  1023. if (this._meshToBoneReferal) {
  1024. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), Tmp.Matrix[6]);
  1025. Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  1026. } else {
  1027. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  1028. }
  1029. }
  1030. } else {
  1031. this._worldMatrix.copyFrom(this._localWorld);
  1032. }
  1033. // Bounding info
  1034. this._updateBoundingInfo();
  1035. // Absolute position
  1036. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  1037. // Callbacks
  1038. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  1039. if (!this._poseMatrix) {
  1040. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  1041. }
  1042. return this._worldMatrix;
  1043. }
  1044. /**
  1045. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  1046. * @param func: callback function to add
  1047. *
  1048. * Returns the AbstractMesh.
  1049. */
  1050. public registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): AbstractMesh {
  1051. this.onAfterWorldMatrixUpdateObservable.add(func);
  1052. return this;
  1053. }
  1054. /**
  1055. * Removes a registered callback function.
  1056. * Returns the AbstractMesh.
  1057. */
  1058. public unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): AbstractMesh {
  1059. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  1060. return this;
  1061. }
  1062. /**
  1063. * Sets the mesh position in its local space.
  1064. * Returns the AbstractMesh.
  1065. */
  1066. public setPositionWithLocalVector(vector3: Vector3): AbstractMesh {
  1067. this.computeWorldMatrix();
  1068. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  1069. return this;
  1070. }
  1071. /**
  1072. * Returns the mesh position in the local space from the current World matrix values.
  1073. * Returns a new Vector3.
  1074. */
  1075. public getPositionExpressedInLocalSpace(): Vector3 {
  1076. this.computeWorldMatrix();
  1077. var invLocalWorldMatrix = this._localWorld.clone();
  1078. invLocalWorldMatrix.invert();
  1079. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  1080. }
  1081. /**
  1082. * Translates the mesh along the passed Vector3 in its local space.
  1083. * Returns the AbstractMesh.
  1084. */
  1085. public locallyTranslate(vector3: Vector3): AbstractMesh {
  1086. this.computeWorldMatrix(true);
  1087. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  1088. return this;
  1089. }
  1090. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  1091. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): AbstractMesh {
  1092. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  1093. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  1094. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  1095. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  1096. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  1097. /// <returns>Mesh oriented towards targetMesh</returns>
  1098. var dv = AbstractMesh._lookAtVectorCache;
  1099. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  1100. targetPoint.subtractToRef(pos, dv);
  1101. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  1102. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  1103. var pitch = Math.atan2(dv.y, len);
  1104. this.rotationQuaternion = this.rotationQuaternion || new Quaternion();
  1105. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  1106. return this;
  1107. }
  1108. public attachToBone(bone: Bone, affectedMesh: AbstractMesh): AbstractMesh {
  1109. this._meshToBoneReferal = affectedMesh;
  1110. this.parent = bone;
  1111. if (bone.getWorldMatrix().determinant() < 0) {
  1112. this.scalingDeterminant *= -1;
  1113. }
  1114. return this;
  1115. }
  1116. public detachFromBone(): AbstractMesh {
  1117. if (this.parent.getWorldMatrix().determinant() < 0) {
  1118. this.scalingDeterminant *= -1;
  1119. }
  1120. this._meshToBoneReferal = null;
  1121. this.parent = null;
  1122. return this;
  1123. }
  1124. /**
  1125. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  1126. * A mesh is in the frustum if its bounding box intersects the frustum.
  1127. * Boolean returned.
  1128. */
  1129. public isInFrustum(frustumPlanes: Plane[]): boolean {
  1130. return this._boundingInfo.isInFrustum(frustumPlanes);
  1131. }
  1132. /**
  1133. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  1134. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  1135. * Boolean returned.
  1136. */
  1137. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  1138. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);;
  1139. }
  1140. /**
  1141. * True if the mesh intersects another mesh or a SolidParticle object.
  1142. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  1143. * Returns a boolean.
  1144. */
  1145. public intersectsMesh(mesh: AbstractMesh | SolidParticle, precise?: boolean): boolean {
  1146. if (!this._boundingInfo || !mesh._boundingInfo) {
  1147. return false;
  1148. }
  1149. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  1150. }
  1151. /**
  1152. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  1153. * Returns a boolean.
  1154. */
  1155. public intersectsPoint(point: Vector3): boolean {
  1156. if (!this._boundingInfo) {
  1157. return false;
  1158. }
  1159. return this._boundingInfo.intersectsPoint(point);
  1160. }
  1161. public getPhysicsImpostor(): PhysicsImpostor {
  1162. return this.physicsImpostor;
  1163. }
  1164. public getPositionInCameraSpace(camera?: Camera): Vector3 {
  1165. if (!camera) {
  1166. camera = this.getScene().activeCamera;
  1167. }
  1168. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  1169. }
  1170. /**
  1171. * Returns the distance from the mesh to the active camera.
  1172. * Returns a float.
  1173. */
  1174. public getDistanceToCamera(camera?: Camera): number {
  1175. if (!camera) {
  1176. camera = this.getScene().activeCamera;
  1177. }
  1178. return this.absolutePosition.subtract(camera.position).length();
  1179. }
  1180. public applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh {
  1181. if (!this.physicsImpostor) {
  1182. return;
  1183. }
  1184. this.physicsImpostor.applyImpulse(force, contactPoint);
  1185. return this;
  1186. }
  1187. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh {
  1188. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  1189. return;
  1190. }
  1191. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {
  1192. mainPivot: pivot1,
  1193. connectedPivot: pivot2,
  1194. nativeParams: options
  1195. });
  1196. return this;
  1197. }
  1198. // Collisions
  1199. /**
  1200. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  1201. * Default `false`.
  1202. */
  1203. public get checkCollisions(): boolean {
  1204. return this._checkCollisions;
  1205. }
  1206. public set checkCollisions(collisionEnabled: boolean) {
  1207. this._checkCollisions = collisionEnabled;
  1208. if (this.getScene().workerCollisions) {
  1209. this.getScene().collisionCoordinator.onMeshUpdated(this);
  1210. }
  1211. }
  1212. public moveWithCollisions(velocity: Vector3): AbstractMesh {
  1213. var globalPosition = this.getAbsolutePosition();
  1214. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  1215. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  1216. if (!this._collider) {
  1217. this._collider = new Collider();
  1218. }
  1219. this._collider.radius = this.ellipsoid;
  1220. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  1221. return this;
  1222. }
  1223. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: AbstractMesh = null) => {
  1224. //TODO move this to the collision coordinator!
  1225. if (this.getScene().workerCollisions)
  1226. newPosition.multiplyInPlace(this._collider.radius);
  1227. newPosition.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  1228. if (this._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {
  1229. this.position.addInPlace(this._diffPositionForCollisions);
  1230. }
  1231. if (collidedMesh) {
  1232. this.onCollideObservable.notifyObservers(collidedMesh);
  1233. }
  1234. this.onCollisionPositionChangeObservable.notifyObservers(this.position);
  1235. }
  1236. // Submeshes octree
  1237. /**
  1238. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  1239. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  1240. * Returns an Octree of submeshes.
  1241. */
  1242. public createOrUpdateSubmeshesOctree(maxCapacity = 64, maxDepth = 2): Octree<SubMesh> {
  1243. if (!this._submeshesOctree) {
  1244. this._submeshesOctree = new Octree<SubMesh>(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  1245. }
  1246. this.computeWorldMatrix(true);
  1247. // Update octree
  1248. var bbox = this.getBoundingInfo().boundingBox;
  1249. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  1250. return this._submeshesOctree;
  1251. }
  1252. // Collisions
  1253. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): AbstractMesh {
  1254. this._generatePointsArray();
  1255. // Transformation
  1256. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  1257. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  1258. subMesh._lastColliderWorldVertices = [];
  1259. subMesh._trianglePlanes = [];
  1260. var start = subMesh.verticesStart;
  1261. var end = (subMesh.verticesStart + subMesh.verticesCount);
  1262. for (var i = start; i < end; i++) {
  1263. subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  1264. }
  1265. }
  1266. // Collide
  1267. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  1268. if (collider.collisionFound) {
  1269. collider.collidedMesh = this;
  1270. }
  1271. return this;
  1272. }
  1273. public _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): AbstractMesh {
  1274. var subMeshes: SubMesh[];
  1275. var len: number;
  1276. // Octrees
  1277. if (this._submeshesOctree && this.useOctreeForCollisions) {
  1278. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  1279. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  1280. len = intersections.length;
  1281. subMeshes = intersections.data;
  1282. } else {
  1283. subMeshes = this.subMeshes;
  1284. len = subMeshes.length;
  1285. }
  1286. for (var index = 0; index < len; index++) {
  1287. var subMesh = subMeshes[index];
  1288. // Bounding test
  1289. if (len > 1 && !subMesh._checkCollision(collider))
  1290. continue;
  1291. this._collideForSubMesh(subMesh, transformMatrix, collider);
  1292. }
  1293. return this;
  1294. }
  1295. public _checkCollision(collider: Collider): AbstractMesh {
  1296. // Bounding box test
  1297. if (!this._boundingInfo._checkCollision(collider))
  1298. return this;
  1299. // Transformation matrix
  1300. Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  1301. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  1302. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  1303. return this;
  1304. }
  1305. // Picking
  1306. public _generatePointsArray(): boolean {
  1307. return false;
  1308. }
  1309. /**
  1310. * Checks if the passed Ray intersects with the mesh.
  1311. * Returns an object PickingInfo.
  1312. */
  1313. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  1314. var pickingInfo = new PickingInfo();
  1315. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  1316. return pickingInfo;
  1317. }
  1318. if (!this._generatePointsArray()) {
  1319. return pickingInfo;
  1320. }
  1321. var intersectInfo: IntersectionInfo = null;
  1322. // Octrees
  1323. var subMeshes: SubMesh[];
  1324. var len: number;
  1325. if (this._submeshesOctree && this.useOctreeForPicking) {
  1326. var worldRay = Ray.Transform(ray, this.getWorldMatrix());
  1327. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  1328. len = intersections.length;
  1329. subMeshes = intersections.data;
  1330. } else {
  1331. subMeshes = this.subMeshes;
  1332. len = subMeshes.length;
  1333. }
  1334. for (var index = 0; index < len; index++) {
  1335. var subMesh = subMeshes[index];
  1336. // Bounding test
  1337. if (len > 1 && !subMesh.canIntersects(ray))
  1338. continue;
  1339. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  1340. if (currentIntersectInfo) {
  1341. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  1342. intersectInfo = currentIntersectInfo;
  1343. intersectInfo.subMeshId = index;
  1344. if (fastCheck) {
  1345. break;
  1346. }
  1347. }
  1348. }
  1349. }
  1350. if (intersectInfo) {
  1351. // Get picked point
  1352. var world = this.getWorldMatrix();
  1353. var worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  1354. var direction = ray.direction.clone();
  1355. direction = direction.scale(intersectInfo.distance);
  1356. var worldDirection = Vector3.TransformNormal(direction, world);
  1357. var pickedPoint = worldOrigin.add(worldDirection);
  1358. // Return result
  1359. pickingInfo.hit = true;
  1360. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  1361. pickingInfo.pickedPoint = pickedPoint;
  1362. pickingInfo.pickedMesh = this;
  1363. pickingInfo.bu = intersectInfo.bu;
  1364. pickingInfo.bv = intersectInfo.bv;
  1365. pickingInfo.faceId = intersectInfo.faceId;
  1366. pickingInfo.subMeshId = intersectInfo.subMeshId;
  1367. return pickingInfo;
  1368. }
  1369. return pickingInfo;
  1370. }
  1371. /**
  1372. * Clones the mesh, used by the class Mesh.
  1373. * Just returns `null` for an AbstractMesh.
  1374. */
  1375. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh {
  1376. return null;
  1377. }
  1378. /**
  1379. * Disposes all the mesh submeshes.
  1380. * Returns the AbstractMesh.
  1381. */
  1382. public releaseSubMeshes(): AbstractMesh {
  1383. if (this.subMeshes) {
  1384. while (this.subMeshes.length) {
  1385. this.subMeshes[0].dispose();
  1386. }
  1387. } else {
  1388. this.subMeshes = new Array<SubMesh>();
  1389. }
  1390. return this;
  1391. }
  1392. /**
  1393. * Disposes the AbstractMesh.
  1394. * Some internal references are kept for further use.
  1395. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  1396. * Returns nothing.
  1397. */
  1398. public dispose(doNotRecurse?: boolean): void {
  1399. var index: number;
  1400. // Action manager
  1401. if (this.actionManager) {
  1402. this.actionManager.dispose();
  1403. this.actionManager = null;
  1404. }
  1405. // Skeleton
  1406. this.skeleton = null;
  1407. // Animations
  1408. this.getScene().stopAnimation(this);
  1409. // Physics
  1410. if (this.physicsImpostor) {
  1411. this.physicsImpostor.dispose(/*!doNotRecurse*/);
  1412. }
  1413. // Intersections in progress
  1414. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  1415. var other = this._intersectionsInProgress[index];
  1416. var pos = other._intersectionsInProgress.indexOf(this);
  1417. other._intersectionsInProgress.splice(pos, 1);
  1418. }
  1419. this._intersectionsInProgress = [];
  1420. // Lights
  1421. var lights = this.getScene().lights;
  1422. lights.forEach((light: Light) => {
  1423. var meshIndex = light.includedOnlyMeshes.indexOf(this);
  1424. if (meshIndex !== -1) {
  1425. light.includedOnlyMeshes.splice(meshIndex, 1);
  1426. }
  1427. meshIndex = light.excludedMeshes.indexOf(this);
  1428. if (meshIndex !== -1) {
  1429. light.excludedMeshes.splice(meshIndex, 1);
  1430. }
  1431. // Shadow generators
  1432. var generator = light.getShadowGenerator();
  1433. if (generator) {
  1434. var shadowMap = generator.getShadowMap();
  1435. meshIndex = shadowMap.renderList.indexOf(this);
  1436. if (meshIndex !== -1) {
  1437. shadowMap.renderList.splice(meshIndex, 1);
  1438. }
  1439. }
  1440. });
  1441. // Edges
  1442. if (this._edgesRenderer) {
  1443. this._edgesRenderer.dispose();
  1444. this._edgesRenderer = null;
  1445. }
  1446. // SubMeshes
  1447. if (this.getClassName() !== "InstancedMesh"){
  1448. this.releaseSubMeshes();
  1449. }
  1450. // Octree
  1451. var sceneOctree = this.getScene().selectionOctree;
  1452. if (sceneOctree) {
  1453. var index = sceneOctree.dynamicContent.indexOf(this);
  1454. if (index !== -1) {
  1455. sceneOctree.dynamicContent.splice(index, 1);
  1456. }
  1457. }
  1458. // Engine
  1459. this.getScene().getEngine().wipeCaches();
  1460. // Remove from scene
  1461. this.getScene().removeMesh(this);
  1462. if (!doNotRecurse) {
  1463. // Particles
  1464. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  1465. if (this.getScene().particleSystems[index].emitter === this) {
  1466. this.getScene().particleSystems[index].dispose();
  1467. index--;
  1468. }
  1469. }
  1470. // Children
  1471. var objects = this.getDescendants(true);
  1472. for (index = 0; index < objects.length; index++) {
  1473. objects[index].dispose();
  1474. }
  1475. } else {
  1476. var childMeshes = this.getChildMeshes(true);
  1477. for (index = 0; index < childMeshes.length; index++) {
  1478. var child = childMeshes[index];
  1479. child.parent = null;
  1480. child.computeWorldMatrix(true);
  1481. }
  1482. }
  1483. // facet data
  1484. if (this._facetDataEnabled) {
  1485. this.disableFacetData();
  1486. }
  1487. this.onAfterWorldMatrixUpdateObservable.clear();
  1488. this.onCollideObservable.clear();
  1489. this.onCollisionPositionChangeObservable.clear();
  1490. this._isDisposed = true;
  1491. super.dispose();
  1492. }
  1493. /**
  1494. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  1495. * This Vector3 is expressed in the World space.
  1496. */
  1497. public getDirection(localAxis:Vector3): Vector3 {
  1498. var result = Vector3.Zero();
  1499. this.getDirectionToRef(localAxis, result);
  1500. return result;
  1501. }
  1502. /**
  1503. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  1504. * localAxis is expressed in the mesh local space.
  1505. * result is computed in the Wordl space from the mesh World matrix.
  1506. * Returns the AbstractMesh.
  1507. */
  1508. public getDirectionToRef(localAxis:Vector3, result:Vector3): AbstractMesh {
  1509. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  1510. return this;
  1511. }
  1512. public setPivotPoint(point:Vector3, space:Space = Space.LOCAL): AbstractMesh {
  1513. if(this.getScene().getRenderId() == 0){
  1514. this.computeWorldMatrix(true);
  1515. }
  1516. var wm = this.getWorldMatrix();
  1517. if (space == Space.WORLD) {
  1518. var tmat = Tmp.Matrix[0];
  1519. wm.invertToRef(tmat);
  1520. point = Vector3.TransformCoordinates(point, tmat);
  1521. }
  1522. Vector3.TransformCoordinatesToRef(point, wm, this.position);
  1523. this._pivotMatrix.m[12] = -point.x;
  1524. this._pivotMatrix.m[13] = -point.y;
  1525. this._pivotMatrix.m[14] = -point.z;
  1526. this._cache.pivotMatrixUpdated = true;
  1527. return this;
  1528. }
  1529. /**
  1530. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  1531. */
  1532. public getPivotPoint(): Vector3 {
  1533. var point = Vector3.Zero();
  1534. this.getPivotPointToRef(point);
  1535. return point;
  1536. }
  1537. /**
  1538. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  1539. * Returns the AbstractMesh.
  1540. */
  1541. public getPivotPointToRef(result:Vector3): AbstractMesh{
  1542. result.x = -this._pivotMatrix.m[12];
  1543. result.y = -this._pivotMatrix.m[13];
  1544. result.z = -this._pivotMatrix.m[14];
  1545. return this;
  1546. }
  1547. /**
  1548. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  1549. */
  1550. public getAbsolutePivotPoint(): Vector3 {
  1551. var point = Vector3.Zero();
  1552. this.getAbsolutePivotPointToRef(point);
  1553. return point;
  1554. }
  1555. /**
  1556. * Defines the passed mesh as the parent of the current mesh.
  1557. * Returns the AbstractMesh.
  1558. */
  1559. public setParent(mesh:AbstractMesh): AbstractMesh {
  1560. var child = this;
  1561. var parent = mesh;
  1562. if(mesh == null){
  1563. var rotation = Tmp.Quaternion[0];
  1564. var position = Tmp.Vector3[0];
  1565. var scale = Tmp.Vector3[1];
  1566. child.getWorldMatrix().decompose(scale, rotation, position);
  1567. if (child.rotationQuaternion) {
  1568. child.rotationQuaternion.copyFrom(rotation);
  1569. } else {
  1570. rotation.toEulerAnglesToRef(child.rotation);
  1571. }
  1572. child.position.x = position.x;
  1573. child.position.y = position.y;
  1574. child.position.z = position.z;
  1575. } else {
  1576. var rotation = Tmp.Quaternion[0];
  1577. var position = Tmp.Vector3[0];
  1578. var scale = Tmp.Vector3[1];
  1579. var m1 = Tmp.Matrix[0];
  1580. var m2 = Tmp.Matrix[1];
  1581. parent.getWorldMatrix().decompose(scale, rotation, position);
  1582. rotation.toRotationMatrix(m1);
  1583. m2.setTranslation(position);
  1584. m2.multiplyToRef(m1, m1);
  1585. var invParentMatrix = Matrix.Invert(m1);
  1586. var m = child.getWorldMatrix().multiply(invParentMatrix);
  1587. m.decompose(scale, rotation, position);
  1588. if (child.rotationQuaternion) {
  1589. child.rotationQuaternion.copyFrom(rotation);
  1590. } else {
  1591. rotation.toEulerAnglesToRef(child.rotation);
  1592. }
  1593. invParentMatrix = Matrix.Invert(parent.getWorldMatrix());
  1594. var m = child.getWorldMatrix().multiply(invParentMatrix);
  1595. m.decompose(scale, rotation, position);
  1596. child.position.x = position.x;
  1597. child.position.y = position.y;
  1598. child.position.z = position.z;
  1599. }
  1600. child.parent = parent;
  1601. return this;
  1602. }
  1603. /**
  1604. * Adds the passed mesh as a child to the current mesh.
  1605. * Returns the AbstractMesh.
  1606. */
  1607. public addChild(mesh:AbstractMesh): AbstractMesh {
  1608. mesh.setParent(this);
  1609. return this;
  1610. }
  1611. /**
  1612. * Removes the passed mesh from the current mesh children list.
  1613. * Returns the AbstractMesh.
  1614. */
  1615. public removeChild(mesh:AbstractMesh): AbstractMesh {
  1616. mesh.setParent(null);
  1617. return this;
  1618. }
  1619. /**
  1620. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  1621. * Returns the AbstractMesh.
  1622. */
  1623. public getAbsolutePivotPointToRef(result:Vector3): AbstractMesh {
  1624. result.x = this._pivotMatrix.m[12];
  1625. result.y = this._pivotMatrix.m[13];
  1626. result.z = this._pivotMatrix.m[14];
  1627. this.getPivotPointToRef(result);
  1628. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  1629. return this;
  1630. }
  1631. // Facet data
  1632. /**
  1633. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  1634. * Returns the AbstractMesh.
  1635. */
  1636. private _initFacetData(): AbstractMesh {
  1637. if (!this._facetNormals) {
  1638. this._facetNormals = new Array<Vector3>();
  1639. }
  1640. if (!this._facetPositions) {
  1641. this._facetPositions = new Array<Vector3>();
  1642. }
  1643. if (!this._facetPartitioning) {
  1644. this._facetPartitioning = new Array<number[]>();
  1645. }
  1646. this._facetNb = this.getIndices().length / 3;
  1647. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  1648. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  1649. for (var f = 0; f < this._facetNb; f++) {
  1650. this._facetNormals[f] = Vector3.Zero();
  1651. this._facetPositions[f] = Vector3.Zero();
  1652. }
  1653. this._facetDataEnabled = true;
  1654. return this;
  1655. }
  1656. /**
  1657. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  1658. * This method can be called within the render loop.
  1659. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  1660. * Returns the AbstractMesh.
  1661. */
  1662. public updateFacetData(): AbstractMesh {
  1663. if (!this._facetDataEnabled) {
  1664. this._initFacetData();
  1665. }
  1666. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1667. var indices = this.getIndices();
  1668. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1669. var bInfo = this.getBoundingInfo();
  1670. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
  1671. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
  1672. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
  1673. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  1674. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  1675. this._subDiv.max = this._partitioningSubdivisions;
  1676. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  1677. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  1678. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  1679. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  1680. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  1681. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  1682. // set the parameters for ComputeNormals()
  1683. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  1684. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  1685. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  1686. this._facetParameters.bInfo = bInfo;
  1687. this._facetParameters.bbSize = this._bbSize;
  1688. this._facetParameters.subDiv = this._subDiv;
  1689. this._facetParameters.ratio = this.partitioningBBoxRatio;
  1690. VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  1691. return this;
  1692. }
  1693. /**
  1694. * Returns the facetLocalNormals array.
  1695. * The normals are expressed in the mesh local space.
  1696. */
  1697. public getFacetLocalNormals(): Vector3[] {
  1698. if (!this._facetNormals) {
  1699. this.updateFacetData();
  1700. }
  1701. return this._facetNormals;
  1702. }
  1703. /**
  1704. * Returns the facetLocalPositions array.
  1705. * The facet positions are expressed in the mesh local space.
  1706. */
  1707. public getFacetLocalPositions(): Vector3[] {
  1708. if (!this._facetPositions) {
  1709. this.updateFacetData();
  1710. }
  1711. return this._facetPositions;
  1712. }
  1713. /**
  1714. * Returns the facetLocalPartioning array.
  1715. */
  1716. public getFacetLocalPartitioning(): number[][] {
  1717. if (!this._facetPartitioning) {
  1718. this.updateFacetData();
  1719. }
  1720. return this._facetPartitioning;
  1721. }
  1722. /**
  1723. * Returns the i-th facet position in the world system.
  1724. * This method allocates a new Vector3 per call.
  1725. */
  1726. public getFacetPosition(i: number): Vector3 {
  1727. var pos = Vector3.Zero();
  1728. this.getFacetPositionToRef(i, pos);
  1729. return pos;
  1730. }
  1731. /**
  1732. * Sets the reference Vector3 with the i-th facet position in the world system.
  1733. * Returns the AbstractMesh.
  1734. */
  1735. public getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh {
  1736. var localPos = (this.getFacetLocalPositions())[i];
  1737. var world = this.getWorldMatrix();
  1738. Vector3.TransformCoordinatesToRef(localPos, world, ref);
  1739. return this;
  1740. }
  1741. /**
  1742. * Returns the i-th facet normal in the world system.
  1743. * This method allocates a new Vector3 per call.
  1744. */
  1745. public getFacetNormal(i: number): Vector3 {
  1746. var norm = Vector3.Zero();
  1747. this.getFacetNormalToRef(i, norm);
  1748. return norm;
  1749. }
  1750. /**
  1751. * Sets the reference Vector3 with the i-th facet normal in the world system.
  1752. * Returns the AbstractMesh.
  1753. */
  1754. public getFacetNormalToRef(i: number, ref: Vector3) {
  1755. var localNorm = (this.getFacetLocalNormals())[i];
  1756. Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  1757. return this;
  1758. }
  1759. /**
  1760. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  1761. */
  1762. public getFacetsAtLocalCoordinates(x: number, y: number, z: number): number[] {
  1763. var bInfo = this.getBoundingInfo();
  1764. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  1765. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  1766. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  1767. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  1768. return null;
  1769. }
  1770. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  1771. }
  1772. /**
  1773. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  1774. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  1775. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  1776. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1777. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  1778. */
  1779. public getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): number {
  1780. var world = this.getWorldMatrix();
  1781. var invMat = Tmp.Matrix[5];
  1782. world.invertToRef(invMat);
  1783. var invVect = Tmp.Vector3[8];
  1784. var closest = null;
  1785. Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  1786. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  1787. if (projected) {
  1788. // tranform the local computed projected vector to world coordinates
  1789. Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  1790. }
  1791. return closest;
  1792. }
  1793. /**
  1794. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  1795. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  1796. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  1797. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1798. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  1799. */
  1800. public getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): number {
  1801. var closest = null;
  1802. var tmpx = 0.0;
  1803. var tmpy = 0.0;
  1804. var tmpz = 0.0;
  1805. var d = 0.0; // tmp dot facet normal * facet position
  1806. var t0 = 0.0;
  1807. var projx = 0.0;
  1808. var projy = 0.0;
  1809. var projz = 0.0;
  1810. // Get all the facets in the same partitioning block than (x, y, z)
  1811. var facetPositions = this.getFacetLocalPositions();
  1812. var facetNormals = this.getFacetLocalNormals();
  1813. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  1814. if (!facetsInBlock) {
  1815. return null;
  1816. }
  1817. // Get the closest facet to (x, y, z)
  1818. var shortest = Number.MAX_VALUE; // init distance vars
  1819. var tmpDistance = shortest;
  1820. var fib; // current facet in the block
  1821. var norm; // current facet normal
  1822. var p0; // current facet barycenter position
  1823. // loop on all the facets in the current partitioning block
  1824. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  1825. fib = facetsInBlock[idx];
  1826. norm = facetNormals[fib];
  1827. p0 = facetPositions[fib];
  1828. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  1829. if ( !checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0) ) {
  1830. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  1831. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  1832. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  1833. projx = x + norm.x * t0;
  1834. projy = y + norm.y * t0;
  1835. projz = z + norm.z * t0;
  1836. tmpx = projx - x;
  1837. tmpy = projy - y;
  1838. tmpz = projz - z;
  1839. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  1840. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  1841. shortest = tmpDistance;
  1842. closest = fib;
  1843. if (projected) {
  1844. projected.x = projx;
  1845. projected.y = projy;
  1846. projected.z = projz;
  1847. }
  1848. }
  1849. }
  1850. }
  1851. return closest;
  1852. }
  1853. /**
  1854. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  1855. */
  1856. public getFacetDataParameters(): any {
  1857. return this._facetParameters;
  1858. }
  1859. /**
  1860. * Disables the feature FacetData and frees the related memory.
  1861. * Returns the AbstractMesh.
  1862. */
  1863. public disableFacetData(): AbstractMesh {
  1864. if (this._facetDataEnabled) {
  1865. this._facetDataEnabled = false;
  1866. this._facetPositions = null;
  1867. this._facetNormals = null;
  1868. this._facetPartitioning = null;
  1869. this._facetParameters = null;
  1870. }
  1871. return this;
  1872. }
  1873. /**
  1874. * Creates new normals data for the mesh.
  1875. * @param updatable.
  1876. */
  1877. public createNormals(updatable: boolean) {
  1878. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1879. var indices = this.getIndices();
  1880. var normals: number[] | Float32Array;
  1881. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1882. normals = this.getVerticesData(VertexBuffer.NormalKind);
  1883. } else {
  1884. normals = [];
  1885. }
  1886. VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  1887. this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
  1888. }
  1889. }
  1890. }